問題出在使用 Tokio 的微服務中,其中連接到 db 和其他異步內容,但是當某些連接失敗時,微服務不會結束作業。當您需要這種情況時它很棒,但是當連接丟失時我需要結束這個微服務的作業......所以你能幫我如何安全關閉程序......?
src/main.rs
use tokio; // 1.0.0
fn main() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(workers_number)
.enable_all()
.build()
.unwrap();
rt.block_on(async {
// health cheacker connection
let health_checker = match HealthChecker::new(some_configuration).await?;
// some connection to db
// ...
// transport client connection
// ...
// so when connection failed or lost I need to
// end process like `std::process::abort()`
// but I cant use it, because its unsafe
let mut task_handler = vec![];
// create some task
join_all(task_handler).await;
});
}
有人有什么想法嗎?
uj5u.com熱心網友回復:
您可以呼叫任何Runtime關閉方法shutdown_timeout或shutdown_background.
如果需要一些等待之王,您可以生成一個任務,該任務tokio::sync::oneshot將在收到信號時觸發關閉。
use core::time::Duration;
use crate::tokio::time::sleep;
use tokio;
fn main() {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
let handle = rt.handle().clone();
let (s, r) = tokio::sync::oneshot::channel();
rt.spawn(async move {
sleep(Duration::from_secs(1)).await;
s.send(0);
});
handle.block_on(async move {
r.await;
rt.shutdown_background();
});
}
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462306.html
上一篇:C#相當于C 延遲異步執行?
下一篇:為什么我得到二元運算子預期的錯誤
