キャッシュ

キャッシュ機能を提供するミドルウェア。

Cacheミドルウェアは、Response内のStatusCodeHeadersBodyに対してキャッシュ機能を提供します。既にキャッシュされた内容がある場合、次回のリクエスト処理時にCacheミドルウェアはメモリ内にキャッシュされた内容を直接クライアントに送信します。

注意:このプラグインはBodyResBody::StreamであるResponseをキャッシュしません。このタイプのResponseに適用された場合、Cacheはこれらのリクエストを処理せず、エラーも引き起こしません。

主な機能

  • CacheIssuerは割り当てられたキャッシュキーの抽象化を提供します。RequestIssuerはその実装の一つで、リクエストのURLのどの部分とリクエストのMethodに基づいてキャッシュキーを生成するかを定義できます。独自のキャッシュキー生成ロジックを定義することも可能です。キャッシュキーは必ずしも文字列型である必要はなく、Hash + Eq + Send + Sync + 'static制約を満たす任意の型をキーとして使用できます。

  • CacheStoreはデータの保存と取得操作を提供します。MokaStoreは組み込みのmokaベースのメモリキャッシュ実装です。独自の実装方法を定義することも可能です。

  • CacheHandlerを実装した構造体で、内部に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>
"#;