Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Faraday middleware that respects HTTP cache

License

NotificationsYou must be signed in to change notification settings

sourcelevel/faraday-http-cache

Repository files navigation

Gem VersionBuild

AFaraday middleware that respects HTTP cache,by checking expiration and validation of the stored responses.

Installation

Add it to your Gemfile:

gem'faraday-http-cache'

Usage and configuration

You have to use the middleware in the Faraday instance that you want to,along with a suitablestore to cache the responses. You can use the newshortcut using a symbol or passing the middleware class

client=Faraday.newdo |builder|builder.use:http_cache,store:Rails.cache# orbuilder.useFaraday::HttpCache,store:Rails.cachebuilder.adapterFaraday.default_adapterend

The middleware accepts astore option for the cache backend responsible for recordingthe API responses that should be stored. Stores should respond towrite,read anddelete,just like an object from theActiveSupport::Cache API.

# Connect the middleware to a Memcache instance.store=ActiveSupport::Cache.lookup_store(:mem_cache_store,['localhost:11211'])client=Faraday.newdo |builder|builder.use:http_cache,store:storebuilder.adapterFaraday.default_adapterend# Or use the Rails.cache instance inside your Rails app.client=Faraday.newdo |builder|builder.use:http_cache,store:Rails.cachebuilder.adapterFaraday.default_adapterend

The default store provided is a simple in memory cache that lives on the client instance.This type of storemight not be persisted across multiple processes or connection instancesso it is probably not suitable for most production environments.Make sure that you configure a store that is suitable for you.

The stdlibJSON module is used for serialization by default, which can struggle with unicodecharacters in responses in Ruby < 3.1. For example, if your JSON returns"name": "Raül" thenyou might see errors like:

Response could not be serialized: "\xC3" from ASCII-8BIT to UTF-8. Try using Marshal to serialize.

For full unicode support, or if you expect to be dealing with images, you can use the stdlibMarshal instead. Alternatively you could use another json library likeoj oryajl-ruby.

client=Faraday.newdo |builder|builder.use:http_cache,store:Rails.cache,serializer:Marshalbuilder.adapterFaraday.default_adapterend

Strategies

You can provide a:strategy option to the middleware to specify the strategy to use.

client=Faraday.newdo |builder|builder.use:http_cache,store:Rails.cache,strategy:Faraday::HttpCache::Strategies::ByVarybuilder.adapterFaraday.default_adapterend

Available strategies are:

Faraday::HttpCache::Strategies::ByUrl

The default strategy.It Uses URL + HTTP method to generate cache keys and stores an array of request + response for each key.

Faraday::HttpCache::Strategies::ByVary

This strategy uses headers fromVary header to generate cache keys.It also uses cache to storeVary headers mapped to the request URL.This strategy is more suitable for caching private responses with the same URLs but different results for different users, likehttps://api.github.com/user.

Note: To automatically remove stale cache keys, you might want to use the:expires_in option.

store=ActiveSupport::Cache.lookup_store(:redis_cache_store,expires_in:1.day,url:'redis://localhost:6379/0')client=Faraday.newdo |builder|builder.use:http_cache,store:store,strategy:Faraday::HttpCache::Strategies::ByVarybuilder.adapterFaraday.default_adapterend

Custom strategies

You can write your own strategy by subclassingFaraday::HttpCache::Strategies::BaseStrategy and implementing#write,#read and#delete methods.

Logging

You can provide a:logger option that will receive debug information based on the middlewareoperations:

client=Faraday.newdo |builder|builder.use:http_cache,store:Rails.cache,logger:Rails.loggerbuilder.adapterFaraday.default_adapterendclient.get('https://site/api/users')# logs "HTTP Cache: [GET users] miss, store"

Instrumentation

In addition to logging you can instrument the middleware by passing in an:instrumenter optionsuch as ActiveSupport::Notifications (compatible objects are also allowed).

The eventhttp_cache.faraday will be published every time the middlewareprocesses a request. In the event payload,:env contains the response Faraday env and:cache_status contains a Symbol indicating the status of the cache processing for that request:

  • :unacceptable means that the request did not go through the cache at all.
  • :miss means that no cached response could be found.
  • :invalid means that the cached response could not be validated against the server.
  • :valid means that the cached responsecould be validated against the server.
  • :fresh means that the cached response was still fresh and could be returned without evencalling the server.
client=Faraday.newdo |builder|builder.use:http_cache,store:Rails.cache,instrumenter:ActiveSupport::Notificationsbuilder.adapterFaraday.default_adapterend# Subscribes to all events from Faraday::HttpCache.ActiveSupport::Notifications.subscribe"http_cache.faraday"do |*args|event=ActiveSupport::Notifications::Event.new(*args)cache_status=event.payload[:cache_status]statsd=Statsd.newcasecache_statuswhen:fresh,:validstatsd.increment('api-calls.cache_hits')when:invalid,:missstatsd.increment('api-calls.cache_misses')when:unacceptablestatsd.increment('api-calls.cache_bypass')endend

See it live

You can clone this repository, install its dependencies with Bundler (runbundle install) andexecute the files under theexamples directory to see a sample of the middleware usage.

What gets cached?

The middleware will use the following headers to make caching decisions:

  • Vary
  • Cache-Control
  • Age
  • Last-Modified
  • ETag
  • Expires

Cache-Control

Themax-age,must-revalidate,proxy-revalidate ands-maxage directives are checked.

Shared vs. non-shared caches

By default, the middleware acts as a "shared cache" per RFC 2616. This means it does not cacheresponses withCache-Control: private. This behavior can be changed by passing in the:shared_cache configuration option:

client=Faraday.newdo |builder|builder.use:http_cache,shared_cache:falsebuilder.adapterFaraday.default_adapterendclient.get('https://site/api/some-private-resource')# => will be cached

License

Copyright (c) 2012-2018 Plataformatec.Copyright (c) 2019 SourceLevel and contributors.

About

A Faraday middleware that respects HTTP cache

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors41

Languages


[8]ページ先頭

©2009-2025 Movatter.jp