pub trait CacheBackend: Send + Sync {
// Required methods
fn get<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<Bytes>>;
fn set_with_ttl<'a>(
&'a self,
key: &'a str,
value: Bytes,
ttl: Duration,
) -> BoxFuture<'a, Result<()>>;
fn remove<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Result<()>>;
fn health_check(&self) -> BoxFuture<'_, bool>;
fn name(&self) -> &'static str;
// Provided method
fn remove_pattern<'a>(
&'a self,
_pattern: &'a str,
) -> BoxFuture<'a, Result<()>> { ... }
}Expand description
Core cache backend trait for both L1 and L2 caches
This trait defines the essential operations that any cache backend must support. Implement this trait to create custom L1 (in-memory) or L2 (distributed) cache backends.
§Required Operations
get: Retrieve a value by keyset_with_ttl: Store a value with a time-to-liveremove: Delete a value by keyhealth_check: Verify cache backend is operational
§Thread Safety
Implementations must be Send + Sync to support concurrent access across async tasks.
§Performance Considerations
getoperations should be optimized for low latency (target: <1ms for L1, <5ms for L2)set_with_ttloperations can be slightly slower but should still be fast- Consider connection pooling for distributed backends
§Example
See module-level documentation for a complete example.
Required Methods§
Sourcefn set_with_ttl<'a>(
&'a self,
key: &'a str,
value: Bytes,
ttl: Duration,
) -> BoxFuture<'a, Result<()>>
fn set_with_ttl<'a>( &'a self, key: &'a str, value: Bytes, ttl: Duration, ) -> BoxFuture<'a, Result<()>>
Sourcefn health_check(&self) -> BoxFuture<'_, bool>
fn health_check(&self) -> BoxFuture<'_, bool>
Check if cache backend is healthy
This method should verify that the cache backend is operational. For distributed caches, this typically involves a ping or connectivity check.
§Returns
true- Cache is healthy and operationalfalse- Cache is unhealthy or unreachable
Provided Methods§
Implementors§
impl CacheBackend for DashMapCache
Implement CacheBackend trait for DashMapCache
impl CacheBackend for MokaCache
Implement CacheBackend trait for MokaCache
impl CacheBackend for RedisCache
Implement CacheBackend trait for RedisCache