有什么方法可以关闭 tokio::runtime::Runtime?
Is there some way how to shutdown tokio::runtime::Runtime?
问题出在 Tokio 的微服务中,其中异步连接到数据库和其他东西,但是当某些连接失败时,微服务不会结束工作。当你需要这种情况时它很棒,但是当连接丢失时我需要结束这个微服务的工作......所以你能帮我如何安全关闭过程......?
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;
});
}
有人有想法吗?
您可以调用任何 Runtime
关闭方法 shutdown_timeout
or 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();
});
}
问题出在 Tokio 的微服务中,其中异步连接到数据库和其他东西,但是当某些连接失败时,微服务不会结束工作。当你需要这种情况时它很棒,但是当连接丢失时我需要结束这个微服务的工作......所以你能帮我如何安全关闭过程......?
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;
});
}
有人有想法吗?
您可以调用任何 Runtime
关闭方法 shutdown_timeout
or 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();
});
}