pub struct CacheLayer<Req, K> { /* private fields */ }Expand description
A Tower Layer that applies response caching to a service.
This layer wraps a service with a Cache middleware that stores
successful responses and returns cached values for subsequent requests
with the same key.
§State Isolation
Note: Each call to layer() creates a new cache store.
If you need multiple services to share the same cache (e.g., when using a
ServiceFactory that creates per-session services), use
SharedCacheLayer instead, or call
.shared() on this layer.
§Examples
use tower_resilience_cache::CacheLayer;
use tower::ServiceBuilder;
use std::time::Duration;
let cache_layer = CacheLayer::builder()
.max_size(100)
.ttl(Duration::from_secs(60))
.key_extractor(|req: &String| req.clone())
.build();
let service = ServiceBuilder::new()
.layer(cache_layer)
.service(my_service());Implementations§
Source§impl<Req, K> CacheLayer<Req, K>
impl<Req, K> CacheLayer<Req, K>
Sourcepub fn new(config: CacheConfig<Req, K>) -> Self
pub fn new(config: CacheConfig<Req, K>) -> Self
Creates a new CacheLayer with the given configuration.
Sourcepub fn builder() -> CacheConfigBuilder<Req, K>
pub fn builder() -> CacheConfigBuilder<Req, K>
Creates a new builder for configuring a cache layer.
§Examples
use tower_resilience_cache::CacheLayer;
use std::time::Duration;
let layer = CacheLayer::builder()
.max_size(100)
.ttl(Duration::from_secs(60))
.key_extractor(|req: &String| req.clone())
.build();Converts this cache layer into a SharedCacheLayer that shares
the cache store across all services created via layer().
This is useful when multiple service instances need to share the same cache, such as when services are created per-session or per-request.
§Type Parameters
Resp: The response type that will be cached. This must match theResponsetype of any service this layer is applied to.
§Examples
use tower_resilience_cache::CacheLayer;
use tower::ServiceBuilder;
use std::time::Duration;
let shared_cache = CacheLayer::builder()
.max_size(100)
.ttl(Duration::from_secs(60))
.key_extractor(|req: &String| req.clone())
.build()
.shared::<String>(); // Specify the response type
// Both services share the same cache
let service1 = ServiceBuilder::new()
.layer(shared_cache.clone())
.service(my_service());
let service2 = ServiceBuilder::new()
.layer(shared_cache)
.service(my_service());Trait Implementations§
Source§impl<Req: Clone, K: Clone> Clone for CacheLayer<Req, K>
impl<Req: Clone, K: Clone> Clone for CacheLayer<Req, K>
Source§fn clone(&self) -> CacheLayer<Req, K>
fn clone(&self) -> CacheLayer<Req, K>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more