Caching wrapper for the LegionIO framework. Provides a consistent interface for Memcached (via dalli) and Redis (via redis gem) with connection pooling. Driver selection is config-driven.
Version: 1.3.0
gem install legion-cacheOr add to your Gemfile:
gem 'legion-cache'require 'legion/cache'
Legion::Cache.setup
Legion::Cache.connected? # => true
# Memcached driver (default) — TTL is a positional argument, default 180s
Legion::Cache.set('foobar', 'testing', 10)
Legion::Cache.get('foobar') # => 'testing'
Legion::Cache.fetch('foobar') # => 'testing' (get with block support)
Legion::Cache.delete('foobar') # => true
Legion::Cache.flush # flush all keys
# Redis driver — TTL is a keyword argument
Legion::Cache.set('foobar', 'testing', ttl: 10)
Legion::Cache.get('foobar') # => 'testing'
Legion::Cache.delete('foobar') # => true
Legion::Cache.flush # flushdb
Legion::Cache.shutdownLegion::Cache supports a two-tier architecture: a shared remote cluster and a local per-machine cache. If the shared cluster is unreachable at setup, all operations transparently fall back to local.
# Shared cache connects to remote cluster; Local connects to localhost
Legion::Cache.setup # starts Local first, then tries shared
Legion::Cache.using_local? # => true if shared was unreachable
Legion::Cache.local # => Legion::Cache::Local
# Use Local directly if needed
Legion::Cache::Local.setup
Legion::Cache::Local.set('key', 'value', 60)
Legion::Cache::Local.get('key') # => 'value'
Legion::Cache::Local.shutdownLocal uses a separate namespace (legion_local) and independent connection pool (pool_size: 5, timeout: 3) so it never collides with the shared tier.
{
"driver": "dalli",
"servers": ["127.0.0.1:11211"],
"connected": false,
"enabled": true,
"namespace": "legion",
"compress": false,
"failover": true,
"threadsafe": true,
"cache_nils": false,
"pool_size": 10,
"timeout": 5,
"expires_in": 0
}The driver is auto-detected at load time: prefers dalli (Memcached) if available, falls back to redis. Override with "driver": "redis" and update servers to point at your Redis instance.
value_max_bytesdefaults to 8MB. Dalli enforces a 1MB client-side limit by default, which silently rejects large values. This default overrides that. Your Memcached server should also be started with-I 8mto match.- Redis default pool size is 20; Memcached default pool size is 10.
{
"driver": "dalli",
"servers": ["127.0.0.1:11211"],
"namespace": "legion_local",
"pool_size": 5,
"timeout": 3
}Override via Legion::Settings[:cache_local].
Legion::Cache.connected? # => true/false
Legion::Cache.size # total pool connections
Legion::Cache.available # idle pool connections
Legion::Cache.restart # close and reconnect pool
Legion::Cache.shutdown # close pool and mark disconnected- Ruby >= 3.4
- Memcached or Redis server
Apache-2.0