为什么我共享的 actix-web 状态有时会重置回原始值?

Why does my shared actix-web state sometimes reset back to the original value?

我正在尝试使用 ArcMutex 在 Actix-Web 框架中实现共享状态。下面的代码可以编译,但是当我 运行 它时,计数器有时会一直回到 0。我如何防止这种情况发生?

use actix_web::{web, App, HttpServer};
use std::sync::{Arc, Mutex};

// This struct represents state
struct AppState {
    app_name: String,
    counter: Arc<Mutex<i64>>,
}

fn index(data: web::Data<AppState>) -> String {
    let mut counter = data.counter.lock().unwrap();
    *counter += 1;
    format!("{}", counter)
}

pub fn main() {
    HttpServer::new(|| {
        App::new()
            .hostname("hello world")
            .register_data(web::Data::new(AppState {
                app_name: String::from("Actix-web"),
                counter: Arc::new(Mutex::new(0)),
            }))
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8088")
    .unwrap()
    .run()
    .unwrap();
}

HttpServer::new 采用一个闭包,为运行服务器的每个线程调用该闭包。这意味着创建了 AppState 的多个实例,每个线程一个。根据响应 HTTP 请求的线程,您将获得不同的 data 实例,因此会得到不同的计数器值。

为防止这种情况发生,请在闭包外创建 web::Data<AppState> 并在 HttpServer::new 闭包内使用克隆引用。