Axum筆記:共享狀態(state)

在不同的應用場景下,經常需要在不同的handlers之間共享一些資源,以便達到更高效/更節約的技術目標,比如:數據庫連接池

Axum有三種方式可以實現狀態的共享

1、State Extractor(推薦模式)

僅允許有一個State

1.1、簡單demo

use axum::Router;
use axum::extract::{State};
use axum::routing::{get, post};

#[derive(Debug, Copy, Clone)]
struct AppVersion {
version: &'static str,
}

async fn hello(State(app_version): State<AppVersion>) -> &'static str {
app_version.version
}

#[tokio::main]
async fn main() {
let app_version = AppVersion {
version: "1.0.0",
};

let app = Router::new()
.route("/hello",get(hello))
.with_state(app_version);

// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}

赞(0)