快取

提供快取功能的中介軟體。

Cache 中介軟體可以對 Response 中的 StatusCodeHeadersBody 提供快取功能。對於已經快取的內容,當下次處理請求時,Cache 中介軟體會直接把快取在記憶體中的內容傳送給客戶端。

注意,此插件不會快取 BodyResBody::StreamResponse。如果應用到這一類型的 Response,Cache 不會處理這些請求,也不會引起錯誤。

主要功能

  • CacheIssuer 提供了對分配的快取鍵值的抽象。RequestIssuer 是它的一個實現,可以定義依據請求的 URL 的哪些部分以及請求的 Method 產生快取的鍵。你也可以定義你自己的快取鍵產生的邏輯。快取的鍵不一定是字串類型,任何滿足 Hash + Eq + Send + Sync + 'static 約束的類型都可以作為鍵。

  • CacheStore 提供對資料的存取操作。MokaStore 是內建的基於 moka 的一個記憶體的快取實現。你也可以定義自己的實現方式。

  • Cache 是實現了 Handler 的結構體,內部還有一個 skipper 欄位,可以指定跳過某些不需要快取的請求。預設情況下,會使用 MethodSkipper 跳過除了 Method::GET 以外的所有請求。

    內部實現範例程式碼:

    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),
          }
      }
    }

從其他框架快速遷移

如果你之前使用過其他框架的快取機制,下面的概念映射將幫助你更快適應Salvo的快取實現:

Rust框架遷移指南

  • 從Actix-web遷移: Actix-web中的actix-web-cache等插件通常需要單獨引入,而Salvo的快取是核心庫的一部分。

    // Actix-web 快取範例
    use actix_web_cache::Cache;
    App::new().wrap(Cache::new().ttl(30))
    
    // Salvo 對應實現
    use salvo::prelude::*;
    Router::new().hoop(Cache::new(MokaStore::new(100), RequestIssuer::new()))

其他語言框架遷移指南

  • 從Go/Gin遷移: Gin使用中介軟體模式,Salvo也採用類似的方式:

    // Gin 快取範例
    store := persist.NewMemoryStore(time.Second * 60)
    router.Use(cache.CachePage(store, time.Second * 30))
    // Salvo 對應實現
    let store = MokaStore::new(100).with_ttl(Duration::from_secs(30));
    router.hoop(Cache::new(store, RequestIssuer::new()))
  • 從Spring Boot遷移: Spring Boot的宣告式快取需要轉換為Salvo的顯式中介軟體配置:

    // Spring Boot
    @Cacheable(value = "books", key = "#isbn")
    public Book findBook(ISBN isbn) { ... }
    // Salvo 對應實現 - 在路由層級應用快取
    let custom_issuer = YourCustomIssuer::new(); // 實現CacheIssuer介面
    Router::with_path("books").hoop(Cache::new(MokaStore::new(100), custom_issuer))
  • 從Express.js遷移: Express的快取中介軟體與Salvo概念上類似,但語法不同:

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

在從其他框架遷移時,需要注意Salvo快取的幾個關鍵概念:

  1. 快取鍵產生 - 透過CacheIssuer介面控制
  2. 快取儲存 - 透過CacheStore介面實現
  3. 快取跳過邏輯 - 透過skipper機制自訂

預設情況下,Salvo僅快取GET請求,這與多數框架的預設行為一致。

範例程式碼

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>
"#;