pub struct RedisCacheMiddlewareBuilder { /* private fields */ }
Expand description
Builder for configuring and creating the RedisCacheMiddleware
.
Provides a fluent interface for configuring cache parameters such as TTL, maximum cacheable size, cache key prefix, and cache decision predicates.
Implementations§
Source§impl RedisCacheMiddlewareBuilder
impl RedisCacheMiddlewareBuilder
Sourcepub fn new(redis_url: impl Into<String>) -> Self
pub fn new(redis_url: impl Into<String>) -> Self
Creates a new builder with the given Redis URL.
§Arguments
redis_url
- The Redis connection URL (e.g., “redis://127.0.0.1:6379”)
§Returns
A new RedisCacheMiddlewareBuilder
with default settings:
- TTL: 3600 seconds (1 hour)
- Max cacheable size: 1MB
- Cache prefix: “cache:”
- Cache predicate: cache all responses
Sourcepub fn max_cacheable_size(self, bytes: usize) -> Self
pub fn max_cacheable_size(self, bytes: usize) -> Self
Sourcepub fn cache_prefix(self, prefix: impl Into<String>) -> Self
pub fn cache_prefix(self, prefix: impl Into<String>) -> Self
Sourcepub fn cache_if<F>(self, predicate: F) -> Self
pub fn cache_if<F>(self, predicate: F) -> Self
Set a predicate function to determine if a response should be cached
Example:
builder.cache_if(|ctx| {
// Only cache GET requests
if ctx.method != "GET" {
return false;
}
// Don't cache if Authorization header is present
if ctx.headers.contains_key("Authorization") {
return false;
}
// Don't cache responses to paths that start with /admin
if ctx.path.starts_with("/admin") {
return false;
}
// Don't cache for a specific route if its body contains some field
if ctx.path.starts_with("/api/users") && ctx.method == "POST" {
return ctx.body.get("role").and_then(|r| r.as_str()) != Some("admin");
}
true
})
Sourcepub fn with_cache_key<F>(self, key_fn: F) -> Self
pub fn with_cache_key<F>(self, key_fn: F) -> Self
Set a custom function to determine the cache key.
By default, cache keys are based on HTTP method, path, query string, and (if present) a hash of the request body. This method lets you specify a custom function to generate the base key before hashing.
Example:
builder.with_cache_key(|ctx| {
// Only use method and path for the cache key (ignore query params and body)
format!("{}:{}", ctx.method, ctx.path)
// Or include specific query parameters
// let user_id = ctx.query_string.split('&')
// .find(|p| p.starts_with("user_id="))
// .unwrap_or("");
// format!("{}:{}:{}", ctx.method, ctx.path, user_id)
})
Sourcepub fn build(self) -> RedisCacheMiddleware
pub fn build(self) -> RedisCacheMiddleware
Builds and returns the configured RedisCacheMiddleware
.
§Returns
A new RedisCacheMiddleware
instance configured with the settings from this builder.