Readthis
Readthis is a drop in replacement for any ActiveSupport compliant cache, but emphasizes performance and simplicity. It takes some cues from Dalli (connection pooling), the popular Memcache client.
For any new projects there isn't any reason to stick with Memcached. Redis is as fast, if not faster in many scenarios, and is far more likely to be used elsewhere in the stack. See this Stack Overflow post for more details.
Footprint & Performance
See Performance
Installation
Add this line to your application's Gemfile:
gem 'readthis'
Usage
Use it the same way as any other ActiveSupport::Cache::Store. Within a rails environment config:
config.cache_store = :readthis_store, ENV.fetch('REDIS_URL'), {
expires_in: 2.weeks.to_i,
namespace: 'cache'
}
Otherwise you can use it anywhere, without any reliance on ActiveSupport:
require 'readthis'
cache = Readthis::Cache.new(ENV.fetch('REDIS_URL'), expires_in: 2.weeks.to_i)
You'll want to use a specific database for caching, just in case you need to clear the cache entirely. Appending a number between 0 and 15 will specify the redis database, which defaults to 0. For example, using database 2:
REDIS_URL=redis://localhost:6379/2
Be sure to use an integer value when setting expiration time. The default
representation of ActiveSupport::Duration values won't work when setting
expiration time, which will cause all keys to have -1 as the TTL. Expiration
values are always cast as an integer on write.
Compression
Compression can be enabled for all actions by passing the compress flag. By
default all values greater than 1024k will be compressed automatically. If there
is any content has not been stored with compression, or perhaps was compressed
but is beneath the compression threshold, it will be passed through as is. This
means it is safe to enable or change compression with an existing cache. There
will be a decoding performance penalty in this case, but it should be minor.
config.cache_store = :readthis_store, ENV.fetch('REDIS_URL'), {
compress: true,
compression_threshold: 2.kilobytes
}
Marshalling
Readthis uses Ruby's Marshal module for dumping and loading all values by
default. This isn't always the fastest option, depending on your use case it may
be desirable to use a faster but less flexible marshaller.
Use Oj for JSON marshalling, extremely fast, but supports limited types:
Readthis::Cache.new(url, marshal: Oj)
If you don't mind everything handles as a string then use the pass-through marshaller:
Readthis::Cache.new(url, marshal: Readthis::Passthrough)
Differences
Readthis supports all of standard cache methods except for the following:
cleanup- redis does this with ttl for us alreadydelete_matched- you really don't want to perform key matching operations in redis. They are linear time and only support basic globbing.