Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: graceful shutdown example #656

Merged
merged 2 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions examples/graceful-shutdown/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "example-graceful-shutdown"
version.workspace = true
edition.workspace = true
publish.workspace = true


[dependencies]
salvo = { workspace = true }
tokio = { workspace = true, features = ["macros", "signal"] }
tracing.workspace = true
tracing-subscriber.workspace = true
48 changes: 48 additions & 0 deletions examples/graceful-shutdown/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use salvo::prelude::*;
use salvo::server::ServerHandle;
use tokio::signal;

#[tokio::main]
async fn main() {
let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
let server = Server::new(acceptor);
let handle = server.handle();

// Listen Shutdown Signal
tokio::spawn(listen_shutdown_signal(handle));

server.serve(Router::new()).await;
}

async fn listen_shutdown_signal(handle: ServerHandle) {
// Wait Shutdown Signal
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};

#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};

#[cfg(windows)]
let terminate = async {
signal::windows::signal(signal::windows::Signal::ctrl_c())
.expect("failed to install signal handler")
.recv()
.await;
};

tokio::select! {
_ = ctrl_c => println!("ctrl_c signal received"),
_ = terminate => println!("terminate signal received"),
};

// Graceful Shutdown Server
handle.stop_graceful(None);
}