我想在 rust 中调用 http rpc,但当前上下文是同步的。然后我尝试像这样调用远程 rpc:
let uniq_id = executor::block_on(get_snowflake_id());
这是get_snowflake_id
功能:
use std::env;
use log::error;
use reqwest::Client;
use rust_wheel::model::response::api_response::ApiResponse;
pub async fn get_snowflake_id() -> Option<i64> {
let client = Client::new();
let infra_url = env::var("INFRA_URL").expect("INFRA_URL must be set");
let url = format!("{}{}", infra_url, "/infra-inner/util/uniqid/gen");
let resp = client
.get(format!("{}", url))
.body("{}")
.send()
.await;
if let Err(e) = resp {
error!("get id failed: {}", e);
return None;
}
let text_response = resp.unwrap().text().await;
if let Err(e) = text_response {
error!("extract text failed: {}", e);
return None;
}
let resp_str = text_response.unwrap_or_default();
let resp_result = serde_json::from_str::<ApiResponse<i64>>(&resp_str);
if let Err(pe) = resp_result {
error!("parse failed: {}, response: {}", pe, &resp_str);
return None;
}
Some(resp_result.unwrap().result)
}
但此代码被永久阻止,我在同步上下文中调用异步代码的方法是否正确?我必须这样做,因为上下文是同步的,我无法将当前上下文调用样式更改为异步。我试过:
pub fn get_uniq_id() -> Option<i64> {
task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(get_snowflake_id())
})
}
显示错误 can call blocking only when running on the multi-threaded runtime
。这是应用程序入口:
#[actix_web::main]
async fn main() -> std::io::Result<()> {}