我正在尝试创建一个Actix服务器,我想使用它作为全局HashMap的接口。
我已经能够创建一个返回整个结构的路由。然而,现在我在更新HashMap时遇到了问题。我可以提交和接收POST请求,但是在尝试使用publish路由和get_topics路由之后,结果HashMap为空{}。
// Publish to topic (creating new topic if none of the same name exists, else update the data)
async fn publish_topic(
topics: web::Data<Mutex<Map<String, Value>>>,
body: web::Bytes,
) -> Result<HttpResponse, Error> {
let result = serde_json::from_str(std::str::from_utf8(&body).unwrap());
let publish_req: Info = match result {
Ok(v) => v,
Err(e) => Info {
topic: "_".to_string(),
data: json!(e.to_string()),
},
};
println!("[ SERVER ]: POST Req: {:?}", publish_req);
topics
.lock()
.unwrap()
.insert(publish_req.topic, publish_req.data);
let map = topics.lock().unwrap().clone();
println!("\n\n{:?}\n\n", topics.lock().unwrap());
let body = serde_json::to_string_pretty(&map).unwrap();
return Ok(HttpResponse::Ok().json(body));
}
#[actix_web::main]
pub async fn start_server() {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let (tx, _) = mpsc::channel();
thread::spawn(move || {
let sys = System::new("http-server");
let srv = HttpServer::new(move || {
let topics: web::Data<Mutex<Map<String, Value>>> =
web::Data::new(Mutex::new(Map::new()));
App::new()
.app_data(topics.clone()) // add shared state
// enable logger
.wrap(middleware::Logger::default())
// register simple handler
.service(web::resource("/").route(web::get().to(get_topics)))
.service(web::resource("/publish").route(web::post().to(publish_topic)))
})
.bind("127.0.0.1:8080")?
.run();
let _ = tx.send(srv);
sys.run()
});
}
发布于 2021-05-31 11:19:36
嗯,你的问题源于你的方法。让我们看一下下面这行:
let srv = HttpServer::new(move || {
let topics: web::Data<Mutex<Map<String, Value>>> =
web::Data::new(Mutex::new(Map::new()));
...
由于actix-web使用application factory来创建新的http服务器,这将告诉它在每个线程中创建一个新的主题映射。我猜这不是你自己想要做的。要解决您的问题,您需要创建主题的实例,并为启动的所有线程创建clone。这将会起作用:
let topics: web::Data<Mutex<Map<String, Value>>> =
web::Data::new(Mutex::new(Map::new()));
HttpServer::new(move || {
App::new()
.app_data(topics.clone())
这个answer也可以作为一个很好的参考。
https://stackoverflow.com/questions/67754144
复制相似问题