gpt4 book ai didi

rust - actix 使用字符串传递应用程序状态

转载 作者:行者123 更新时间:2023-12-03 11:42:26 27 4
gpt4 key购买 nike

您好,我想传递以下 AppState。

pub struct AppState {
clients: Vec<Client>,
}

这就是我的服务器:

async fn launch_server(app_config: CmkClientServerConfig) -> std::io::Result<()> {
HttpServer::new(|| App::new()
.data(Config::default().realm("Restricted area"))
.data(AppState {
clients: app_config.clients
})
.app_data(web::PayloadConfig::new(1000000))
.service(web::resource("/").route(web::post().to(index))))
.bind("127.0.0.1:8080")?
.workers(1)
.run()
.await
}

我想要传递的客户端实体结构:

#[derive(Serialize, Deserialize, Debug)]
pub struct Client {
pub id: String,
pub password: String,
}

我希望大家清楚我要实现的目标。现在我的问题。编译器说:

the trait bound entities::CmkClientServerConfig: std::clone::Clone is not satisfied in `[closure@src/server.rs:25:21: 31:66 app_config:entities::CmkClientServerConfig]

也许由于异步执行,这个东西需要克隆。因此,将“#[derive(Clone)]”添加到 CmkClientServerConfig 结构和 Client 结构中。

然后得到这个错误消息:

error[E0507]: cannot move out of `app_config.clients`, as `app_config` is a captured variable in an `Fn` closure
--> src/server.rs:29:22
|
23 | async fn launch_server(app_config: CmkClientServerConfig) -> std::io::Result<()> {
| ---------- captured outer variable
...
29 | clients: app_config.clients
| ^^^^^^^^^^^^^^^^^^ move occurs because `app_config.clients` has type `std::vec::Vec<entities::Client>`, which does not implement the `Copy` trait

error[E0507]: cannot move out of `app_config.clients`, as `app_config` is a captured variable in an `Fn` closure
--> src/server.rs:29:22
|
23 | async fn launch_server(app_config: CmkClientServerConfig) -> std::io::Result<()> {
| ---------- captured outer variable
...
29 | clients: app_config.clients
| ^^^^^^^^^^^^^^^^^^ move occurs because `app_config.clients` has type `std::vec::Vec<entities::Client>`, which does not implement the `Copy` trait

我的问题是如何正确地做到这一点,如何使克隆成为可能。

感谢您的帮助。

最佳答案

我认为你需要解决app_config.clients的问题被感动。就这样您就在同一页面上,clojure 传递到 HttpServer::new每个线程将执行一次。因此这会导致多次移出 app_config.clients 。 (想一想你就会明白actix是如何工作的)。

也就是说,这个问题可以通过以下方式之一来处理,具体取决于哪些可能:

  1. 创建新的Vec<Client>对于每个线程,如下所示:
...
.data(AppState {
clients: create_new_clients()
})
  • 如果您的Client结构是Clone你还可以这样做:
  • ...
    .data(AppState {
    clients: app_config.clients.clone()
    })
  • 如果一切都失败了,您可以将您的客户包裹在Arc内像这样:
  • pub struct AppState {
    clients: Vec<Arc<Client>>,
    }
    ...
    .data(AppState {
    clients: app_config.clients.clone()
    })

    Client可能需要可变性,请检查建议的其他答案 Arc<Mutex<Client>>为此

    关于rust - actix 使用字符串传递应用程序状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65466800/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com