#固定狀態 請求中的共享數據
固定狀態中介軟體用於在 Depot 中新增共享數據。
若要使用固定狀態功能,需在 Cargo.toml 中啟用 affix-state 特性。
#功能解析
固定狀態提供了一種在請求處理過程中共享數據的簡便方式。它允許您:
在路由配置階段注入全域配置或共享數據 透過 Depot 在任何處理器中存取這些數據 支援任何可複製的類型作為狀態數據
#與其他框架對比 快速理解概念
| 框架 | 語言 | 狀態管理方式 |
|---|---|---|
| Salvo (固定狀態) | Rust | 透過 Depot 儲存與存取,支援多種類型 |
| Axum | Rust | 透過 Extension 儲存狀態,類似但使用方式不同 |
| Actix-web | Rust | 使用 App Data 和 Web::Data 共享狀態 |
| Gin | Go | 使用 context.Set 和 context.Get 存取數據 |
| Echo | Go | 使用 context.Set 和 context.Get 管理共享狀態 |
| Spring | Java | 使用 ApplicationContext 或 @Bean 註解管理依賴 |
| Quarkus | Java | 使用 CDI 和依賴注入機制 |
| Express.js | JavaScript | 使用 app.locals 或 req.app.locals 儲存全域狀態 |
| Nest.js | JavaScript | 使用依賴注入系統管理共享服務 |
| Koa.js | JavaScript | 使用 ctx.state 儲存請求層級狀態 |
#常見使用場景
- 資料庫連接池共享
- 應用程式配置共享
- 快取實例共享
- API 客戶端共享
- 全域計數器或狀態追蹤
固定狀態的優勢在於其簡潔性與靈活性,能夠輕鬆在不同路由與處理器之間共享任何類型的數據,而無需大量樣板程式碼。 範例程式碼
main.rs
Cargo.toml
use std::sync::Arc;
use std::sync::Mutex;
use salvo::prelude::*;
// Configuration structure with username and password
#[allow(dead_code)]
#[derive(Default, Clone, Debug)]
struct Config {
username: String,
password: String,
}
// State structure to hold a list of fail messages
#[derive(Default, Debug)]
struct State {
fails: Mutex<Vec<String>>,
}
#[handler]
async fn hello(depot: &mut Depot) -> String {
// Obtain the Config instance from the depot
let config = depot.obtain::<Config>().unwrap();
// Get custom data from the depot
let custom_data = depot.get::<&str>("custom_data").unwrap();
// Obtain the shared State instance from the depot
let state = depot.obtain::<Arc<State>>().unwrap();
// Lock the fails vector and add a new fail message
let mut fails_ref = state.fails.lock().unwrap();
fails_ref.push("fail message".into());
// Format and return the response string
format!("Hello World\nConfig: {config:#?}\nFails: {fails_ref:#?}\nCustom Data: {custom_data}")
}
#[tokio::main]
async fn main() {
// Initialize the tracing subscriber for logging
tracing_subscriber::fmt().init();
// Create a Config instance with default username and password
let config = Config {
username: "root".to_string(),
password: "pwd".to_string(),
};
// Set up the router with state injection and custom data
let router = Router::new()
// Use hoop to inject middleware and data into the request context
.hoop(
affix_state::inject(config)
// Inject a shared State instance into the request context
.inject(Arc::new(State {
fails: Mutex::new(Vec::new()),
}))
// Insert custom data into the request context
.insert("custom_data", "I love this world!"),
)
// Register the hello handler for the root path
.get(hello)
// Add an additional route for the path "/hello" with the same handler
.push(Router::with_path("hello").get(hello));
// Bind the server to port 8698 and start serving
let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
Server::new(acceptor).serve(router).await;
}
[package]
name = "example-affix-state"
version.workspace = true
edition.workspace = true
publish.workspace = true
rust-version.workspace = true
[dependencies]
salvo = { workspace = true, features = ["affix-state"] }
tokio = { workspace = true, features = ["macros"] }
tracing.workspace = true
tracing-subscriber.workspace = true