class Routemaster::Cache
Caches GET requests.
Emits ‘cache_bust`, `cache_hit`, and `cache_miss` events.
The requests themselves are handled by {APIClient}. Note that ‘Cache-Control` headers are intentionally ignored, as it is assumed one will call {#bust} when the cache becomes stale.
This is for instance done automatically by {Middleware::Cache} upon receiving events from Routemaster
.
Public Class Methods
# File lib/routemaster/cache.rb, line 21 def initialize(redis: nil, client: nil, client_options: {}) @redis = redis || Config.cache_redis @client = client || APIClient.new(client_options.merge(listener: self)) end
Public Instance Methods
This is because wisper makes broadcasting methods private
# File lib/routemaster/cache.rb, line 37 def _publish(event, url) publish(event, url) end
Bust the cache for a given URL
# File lib/routemaster/cache.rb, line 27 def bust(url) @redis.del(Routemaster::CacheKey.url_key(url)) _publish(:cache_bust, url) end
Like {#get}, but schedules any request in the background using a thread pool. Handy to issue lots of requests in parallel.
@return [ResponsePromise], which responds to ‘status`, `headers`, and `body` like [Response].
# File lib/routemaster/cache.rb, line 60 def fget(url, version: nil, locale: nil) @client.fget(url, headers: headers(version: version, locale: locale)) end
Get the response from a URL, from the cache if possible. Stores to the cache on misses.
Different versions and locales are stored separately in the cache.
@param version [Integer] The version to pass in headers, as ‘Accept: application/json;v=2` @param locale [String] The language to request in the `Accept-Language` header.
@return [Response], which responds to ‘status`, `headers`, and `body`.
# File lib/routemaster/cache.rb, line 51 def get(url, version: nil, locale: nil) @client.get(url, headers: headers(version: version, locale: locale)) end
# File lib/routemaster/cache.rb, line 32 def invalidate(url) EventIndex.new(url, cache: @redis).increment end
Private Instance Methods
# File lib/routemaster/cache.rb, line 66 def headers(version: nil, locale: nil) @headers ||= {}.tap do |hash| hash['Accept'] = version ? "application/json;v=#{version}" : "application/json" hash['Accept-Language'] = locale if locale end end