Cache

Fornisce un middleware per la funzionalità di caching.

Il middleware Cache può memorizzare nella cache StatusCode, Headers e Body di una Response. Per i contenuti già memorizzati, alla successiva richiesta, il middleware Cache invierà direttamente al client il contenuto salvato in memoria.

Nota: questo plugin non memorizzerà Response con Body di tipo ResBody::Stream. Se applicato a questo tipo di Response, Cache non elaborerà queste richieste ma non causerà errori.

Funzionalità principali

  • CacheIssuer fornisce un'astrazione per la generazione delle chiavi di cache. RequestIssuer è una sua implementazione che permette di definire quali parti dell'URL della richiesta e del Method usare per generare la chiave. Puoi anche definire la tua logica per generare chiavi. La chiave non deve essere necessariamente una stringa: qualsiasi tipo che soddisfi i vincoli Hash + Eq + Send + Sync + 'static può essere usato come chiave.

  • CacheStore fornisce operazioni di lettura/scrittura dei dati. MokaStore è un'implementazione integrata basata su moka per la cache in memoria. Puoi anche definire la tua implementazione.

  • Cache è una struttura che implementa Handler, con un campo skipper interno per specificare quali richieste saltare (non memorizzare). Per default, usa MethodSkipper per saltare tutte le richieste tranne quelle con Method::GET.

    Codice di esempio dell'implementazione interna:

    impl<S, I> Cache<S, I> {
      pub fn new(store: S, issuer: I) -> Self {
          let skipper = MethodSkipper::new().skip_all().skip_get(false);
          Cache {
              store,
              issuer,
              skipper: Box::new(skipper),
          }
      }
    }

Migrazione rapida da altri framework

Se hai usato meccanismi di caching in altri framework, queste corrispondenze concettuali ti aiuteranno ad adattarti più rapidamente all'implementazione di Salvo:

Guida alla migrazione da framework Rust

  • Da Actix-web: I plugin come actix-web-cache in Actix-web richiedono un'introduzione separata, mentre il caching in Salvo fa parte della libreria core.

    // Esempio di cache in Actix-web
    use actix_web_cache::Cache;
    App::new().wrap(Cache::new().ttl(30))
    
    // Implementazione corrispondente in Salvo
    use salvo::prelude::*;
    Router::new().hoop(Cache::new(MokaStore::new(100), RequestIssuer::new()))

Guida alla migrazione da framework in altri linguaggi

  • Da Go/Gin: Gin usa il pattern middleware, come anche Salvo:

    // Esempio di cache in Gin
    store := persist.NewMemoryStore(time.Second * 60)
    router.Use(cache.CachePage(store, time.Second * 30))
    // Implementazione corrispondente in Salvo
    let store = MokaStore::new(100).with_ttl(Duration::from_secs(30));
    router.hoop(Cache::new(store, RequestIssuer::new()))
  • Da Spring Boot: Il caching dichiarativo di Spring Boot va convertito in configurazione esplicita del middleware in Salvo:

    // Spring Boot
    @Cacheable(value = "books", key = "#isbn")
    public Book findBook(ISBN isbn) { ... }
    // Implementazione corrispondente in Salvo - applica cache a livello di route
    let custom_issuer = YourCustomIssuer::new(); // implementa l'interfaccia CacheIssuer
    Router::with_path("books").hoop(Cache::new(MokaStore::new(100), custom_issuer))
  • Da Express.js: Il middleware di cache di Express è concettualmente simile a Salvo, ma con sintassi diversa:

    // Express.js
    const apicache = require('apicache');
    app.use(apicache.middleware('5 minutes'));
    
    // Implementazione corrispondente in Salvo
    let store = MokaStore::new(100).with_ttl(Duration::from_secs(300));
    router.hoop(Cache::new(store, RequestIssuer::new()))

Nella migrazione da altri framework, nota questi concetti chiave del caching in Salvo:

  1. Generazione chiavi cache - controllata dall'interfaccia CacheIssuer
  2. Memorizzazione cache - implementata con l'interfaccia CacheStore
  3. Logica di esclusione - personalizzabile con il meccanismo skipper

Per default, Salvo memorizza solo richieste GET, comportamento comune alla maggior parte dei framework.

Codice di esempio

main.rs
Cargo.toml
cache-simple/src/main.rs
use std::time::Duration;

use salvo::cache::{Cache, MokaStore, RequestIssuer};
use salvo::prelude::*;
use salvo::writing::Text;
use time::OffsetDateTime;

// Handler for serving the home page with HTML content
#[handler]
async fn home() -> Text<&'static str> {
    Text::Html(HOME_HTML)
}

// Handler for short-lived cached response (5 seconds)
#[handler]
async fn short() -> String {
    format!(
        "Hello World, my birth time is {}",
        OffsetDateTime::now_utc()
    )
}

// Handler for long-lived cached response (1 minute)
#[handler]
async fn long() -> String {
    format!(
        "Hello World, my birth time is {}",
        OffsetDateTime::now_utc()
    )
}

#[tokio::main]
async fn main() {
    // Initialize logging system
    tracing_subscriber::fmt().init();

    // Create cache middleware for short-lived responses (5 seconds TTL)
    let short_cache = Cache::new(
        MokaStore::builder()
            .time_to_live(Duration::from_secs(5))
            .build(),
        RequestIssuer::default(),
    );

    // Create cache middleware for long-lived responses (60 seconds TTL)
    let long_cache = Cache::new(
        MokaStore::builder()
            .time_to_live(Duration::from_secs(60))
            .build(),
        RequestIssuer::default(),
    );

    // Set up router with three endpoints:
    // - / : Home page
    // - /short : Response cached for 5 seconds
    // - /long : Response cached for 1 minute
    let router = Router::new()
        .get(home)
        .push(Router::with_path("short").hoop(short_cache).get(short))
        .push(Router::with_path("long").hoop(long_cache).get(long));

    // Bind server to port 5800 and start serving
    let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
    Server::new(acceptor).serve(router).await;
}

// HTML template for the home page with links to cached endpoints
static HOME_HTML: &str = r#"
<!DOCTYPE html>
<html>
    <head>
        <title>Cache Example</title>
    </head>
    <body>
        <h2>Cache Example</h2>
        <p>
            This examples shows how to use cache middleware.
        </p>
        <p>
            <a href="/short" target="_blank">Cache 5 seconds</a>
        </p>
        <p>
            <a href="/long" target="_blank">Cache 1 minute</a>
        </p>
    </body>
</html>
"#;