Cache
Middleware that provides caching functionality.
The Cache middleware can cache the StatusCode, Headers, and Body of a Response. For content that has already been cached, the Cache middleware will directly send the cached content from memory to the client when processing subsequent requests.
Note: This plugin does not cache Response objects whose Body is ResBody::Stream. If applied to such a Response, Cache will not process these requests, and no error will occur.
Main Features
-
CacheIssuerprovides an abstraction for generating cache keys.RequestIssueris one of its implementations, allowing you to define which parts of the request URL and the requestMethodshould be used to generate the cache key. You can also define your own cache key generation logic. The cache key does not necessarily have to be a string; any type that satisfies theHash + Eq + Send + Sync + 'staticconstraints can be used as a key. -
CacheStoreprovides operations for storing and retrieving data.MokaStoreis a built-in memory-based cache implementation based onmoka. You can also define your own implementation. -
Cacheis a struct that implementsHandler. It also contains an internalskipperfield, which can be used to specify requests that should skip caching. By default, it usesMethodSkipperto skip all requests except those withMethod::GET.Example internal implementation code:
Quick Migration from Other Frameworks
If you have used caching mechanisms in other frameworks, the following conceptual mappings will help you adapt to Salvo's caching implementation more quickly:
Rust Framework Migration Guide
-
Migrating from Actix-web: Plugins like
actix-web-cachein Actix-web typically need to be introduced separately, whereas caching in Salvo is part of the core library.
Migration Guide for Frameworks in Other Languages
-
Migrating from Go/Gin: Gin uses a middleware pattern, which Salvo also adopts in a similar manner:
-
Migrating from Spring Boot: Spring Boot's declarative caching needs to be converted to Salvo's explicit middleware configuration:
-
Migrating from Express.js: Express's caching middleware is conceptually similar to Salvo's, but the syntax differs:
When migrating from other frameworks, pay attention to several key concepts of Salvo's caching:
- Cache Key Generation - Controlled via the
CacheIssuerinterface. - Cache Storage - Implemented via the
CacheStoreinterface. - Cache Skipping Logic - Customized via the
skippermechanism.
By default, Salvo only caches GET requests, which aligns with the default behavior of most frameworks.
Example Code