Expand description
Response caching middleware for the Salvo web framework.
This middleware intercepts HTTP responses and caches them for subsequent requests, reducing server load and improving response times for cacheable content.
§What Gets Cached
The cache stores the complete response including:
- HTTP status code
- Response headers
- Response body (except for streaming responses)
§Key Components
CacheIssuer: Determines the cache key for each requestCacheStore: Backend storage for cached responsesCache: The middleware handler
§Default Implementations
RequestIssuer: Generates cache keys from the request URI and methodMokaStore: High-performance concurrent cache backed bymoka
§Example
ⓘ
use std::time::Duration;
use salvo_cache::{Cache, MokaStore, RequestIssuer};
use salvo_core::prelude::*;
let cache = Cache::new(
MokaStore::builder()
.time_to_live(Duration::from_secs(300)) // Cache for 5 minutes
.build(),
RequestIssuer::default(),
);
let router = Router::new()
.hoop(cache)
.get(my_expensive_handler);§Custom Cache Keys
Implement CacheIssuer to customize cache key generation:
ⓘ
use salvo_cache::CacheIssuer;
struct UserBasedIssuer;
impl CacheIssuer for UserBasedIssuer {
type Key = String;
async fn issue(&self, req: &mut Request, depot: &Depot) -> Option<Self::Key> {
// Cache per user + path
let user_id = depot.get::<String>("user_id").ok()?;
Some(format!("{}:{}", user_id, req.uri().path()))
}
}§Skipping Cache
By default, only GET requests are cached. Use the skipper method to customize:
ⓘ
let cache = Cache::new(store, issuer)
.skipper(|req, _depot| req.uri().path().starts_with("/api/"));§Limitations
- Streaming responses (
ResBody::Stream) cannot be cached - Error responses are not cached
Read more: https://salvo.rs
Re-exports§
pub use moka_store::MokaStore;moka-store
Modules§
- moka_
store moka-store - Memory store module.
Structs§
- Cache
- Cache middleware.
- Cached
Entry - Cached entry which will be stored in the cache store.
- Method
Skipper - Skipper for
Method. You can use it to skip some methods. - Request
Issuer - Identify user by Request Uri.
Enums§
- Cached
Body CachedBodyis used to save the response body toCacheStore.
Traits§
- Cache
Issuer - Issuer
- Cache
Store - Store cache.