CacheKeeper
Have your cached methods refreshed asynchronously and automatically.
CacheKeeper is a Rails gem that allows you to mark any method to be kept fresh in your cache. It uses ActiveJob to refresh the cache in the background, either on demand or periodically.
Installation
Add CacheKeeper to your Gemfile:
bundle add cache_keeper
Usage
CacheKeeper provides a caches method that will cache the result of the methods you give it:
caches :slow_method, :really_slow_method, expires_in: 1.hour
caches :incredibly_slow_method, expires_in: 2.hours, must_revalidate: true
It's automatically available in your ActiveRecord models and in your controllers. You can also use it in any other class by including CacheKeeper::Caching.
By default, it will immediately run the method call if it hasn't been cached before. The next time it is called, it will return the cached value if it hasn't expired yet. If it has expired, it will enqueue a job to refresh the cache in the background and return the stale value in the meantime. You can avoid returning stale values by setting must_revalidate: true in the options.
It's important to note that it will only work with methods that don't take any arguments.
Autorefresh
You can tell CacheKeeper to automatically refresh the cache after a certain amount of time by setting the autorefresh option:
caches :i_cant_even, expires_in: 2.hours, autorefresh: true
This works by running a job in cron mode that will periodically check for stale entries and enqueue a job to refresh them. You need to specify an adapter as explained in the configuration section below.
Configuration
CacheKeeper can be configured in an initializer, in any environment file or in your config/application.rb file. The following options are available:
Rails.application.configure do
# If a stale entry is requested, refresh immediately instead of enqueuing a refresh job.
# Default: false
config.cache_keeper.must_revalidate = true
# The queue to use for the refresh jobs.
# Default: nil (uses the default queue)
config.cache_keeper.queues.refresh = :low_priority
# The adapter to use for the autorefresh cron job.
# Options: :good_job
# Default: nil
config.cache_keeper.cron.adapter = :good_job
# The cron expression to use for the autorefresh cron job.
# Default: "*/15 * * * *" (every 15 minutes)
config.cache_keeper.cron.expression = "0 * * * *"
end
Development
Running the tests
- You can run the whole suite with `./bin/test test/**/*_test.rb`
License
CacheKeeper is released under the MIT License.