| Crates.io | actix-request-reply-cache |
| lib.rs | actix-request-reply-cache |
| version | 0.1.7 |
| created_at | 2025-04-25 20:30:10.723378+00 |
| updated_at | 2025-04-25 23:53:58.16686+00 |
| description | A simple request/reply cache middleware for Actix Web with Redis backend |
| homepage | |
| repository | https://github.com/densumesh/actix-request-reply-cache |
| max_upload_size | |
| id | 1649437 |
| size | 40,025 |
A Redis-backed response caching middleware for Actix Web applications.
Add this to your Cargo.toml:
[dependencies]
actix-request-reply-cache = "0.1.0"
use actix_web::{web, App, HttpServer};
use actix_request_reply_cache::RedisCacheMiddlewareBuilder;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Create the cache middleware with default settings
let cache = RedisCacheMiddlewareBuilder::new("redis://127.0.0.1:6379")
.build()
.await;
HttpServer::new(move || {
App::new()
.wrap(cache.clone())
.service(web::resource("/").to(|| async { "Hello world!" }))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
use actix_web::{web, App, HttpServer};
use actix_request_reply_cache::RedisCacheMiddlewareBuilder;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Create a more customized cache middleware
let cache = RedisCacheMiddlewareBuilder::new("redis://127.0.0.1:6379")
.ttl(300) // Cache for 5 minutes
.max_cacheable_size(512 * 1024) // Only cache responses <= 512KB
.cache_prefix("my-api-cache:") // Custom Redis key prefix
.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 admin routes
if ctx.path.starts_with("/admin") {
return false;
}
true
})
.build()
.await;
HttpServer::new(move || {
App::new()
.wrap(cache.clone())
.service(web::resource("/api/users").to(get_users))
.service(web::resource("/api/products").to(get_products))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
The cache_if predicate receives a CacheDecisionContext with the following information:
method: HTTP method string ("GET", "POST", etc.)path: Request pathquery_string: URL query parametersheaders: HTTP request headersbody: Request body as bytesThis allows for fine-grained control over what gets cached.
This project is licensed under the MIT License.