Skip to main content
CacheModule gives you an injectable CacheService that works out of the box with an in-memory store and optionally upgrades to Redis for multi-instance deployments. The API is the same regardless of backend: get, set, del, and ttl. Enable the cache feature in Cargo.toml, register the module with CacheModule::register(CacheOptions::in_memory()), and inject CacheService into any provider.

Enable the feature

Register CacheModule

Pass CacheOptions::in_memory() to CacheModule::register in your module’s imports list. The returned DynamicModule exports CacheService for injection.

Inject and use CacheService

CacheService is injected as Arc<CacheService>. Use get::<T> for typed deserialization or get_json when you want a raw serde_json::Value.

Operations reference

1

set — store a value with optional TTL

set serializes any Serialize type and stores it under a key. Pass Some(Duration::from_secs(60)) to expire the entry after 60 seconds, or None to keep it indefinitely.
2

get — retrieve a typed value

get::<T> deserializes the stored JSON into your type. Returns Ok(None) when the key is missing or expired.
3

get_json — retrieve raw JSON

When you want the raw serde_json::Value without a concrete type, use get_json. Returns None on a cache miss or expiry.
4

del — remove an entry

del removes the key and returns true if the key existed, false if it was already absent.
5

ttl — inspect remaining lifetime

ttl returns the Duration left before expiry, or None if the key has no TTL or does not exist.

CacheOptions

CacheOptions is an enum with two variants. You select the backend at registration time, not at injection time.

Redis backend

Enable the cache-redis feature alongside cache, then pass CacheOptions::redis(url) to register. The Redis client is lazy — the connection is established on the first cache operation.

RedisCacheOptions with a key prefix

For applications that share one Redis instance across multiple services, use RedisCacheOptions directly to add a prefix. All keys will be stored as prefix:key.
Redis TTLs use millisecond precision internally (via the PX option on SET) to match the granularity of the in-memory backend.

set_json — low-level raw JSON store

If you already have a serde_json::Value and want to skip the serialization step, use set_json directly:

Troubleshooting