【发布时间】:2021-11-29 13:46:51
【问题描述】:
rust-actix
尝试从 actix-web 运行演员时在 spawn_local 出现恐慌
我正在尝试在 actix-web 服务器中启动一个演员并使用数据传递其地址。
use actix::prelude::*;
use actix_web::{web, App, HttpRequest, HttpServer, Responder};
struct MyActor;
impl Actor for MyActor {
type Context = Context<Self>;
}
struct AppState {
actor_addr: Addr<MyActor>,
}
async fn greet(req: HttpRequest, data: web::Data<AppState>) -> impl Responder {
format!("Hello!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let addr = MyActor.start();
HttpServer::new(move || {
App::new()
.data(AppState {
actor_addr: addr.clone(),
})
.route("/", web::get().to(greet))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
这个想法是从 greet 函数向actor发送消息。当试图运行它时,我得到以下恐慌:
thread 'main' panicked at '`spawn_local` called from outside of a `task::LocalSet`', /Users/myuser/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.12.0/src/task/local.rs:305:18
我尝试将#[actix_web::main] 替换为#[actix_rt::main],它启动了actor。
潜伏代码,我意识到#[actix_web::main] 是#[actix_rt::main] 的再导出,所以它应该可以工作。
依赖版本是:
actix-web = "3.3.2"
actix = "0.12.0"
可能依赖项不匹配。
这是实现我正在尝试的方式吗?
提前致谢。
【问题讨论】:
标签: rust rust-actix