mirror of
https://github.com/tokio-rs/axum.git
synced 2025-04-26 13:56:22 +02:00
Add graceful shutdown example (#349)
This commit is contained in:
parent
f3c155bf5b
commit
0b3ee5b2ce
2 changed files with 64 additions and 0 deletions
examples/graceful_shutdown
9
examples/graceful_shutdown/Cargo.toml
Normal file
9
examples/graceful_shutdown/Cargo.toml
Normal file
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "example-graceful-shutdown"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
axum = { path = "../.." }
|
||||
tokio = { version = "1.0", features = ["full"] }
|
55
examples/graceful_shutdown/src/main.rs
Normal file
55
examples/graceful_shutdown/src/main.rs
Normal file
|
@ -0,0 +1,55 @@
|
|||
//! Run with
|
||||
//!
|
||||
//! ```not_rust
|
||||
//! cargo run -p example-graceful-shutdown
|
||||
//! kill or ctrl-c
|
||||
//! ```
|
||||
|
||||
use axum::{handler::get, response::Html, Router};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// build our application with a route
|
||||
let app = Router::new().route("/", get(handler));
|
||||
|
||||
// run it
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
println!("listening on {}", addr);
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn handler() -> Html<&'static str> {
|
||||
Html("<h1>Hello, World!</h1>")
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub async fn shutdown_signal() {
|
||||
use std::io;
|
||||
use tokio::signal::unix::SignalKind;
|
||||
|
||||
async fn terminate() -> io::Result<()> {
|
||||
tokio::signal::unix::signal(SignalKind::terminate())?
|
||||
.recv()
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = terminate() => {},
|
||||
_ = tokio::signal::ctrl_c() => {},
|
||||
}
|
||||
println!("signal received, starting graceful shutdown")
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub async fn shutdown_signal() {
|
||||
tokio::signal::ctrl_c()
|
||||
.await
|
||||
.expect("faild to install CTRL+C handler");
|
||||
println!("signal received, starting graceful shutdown")
|
||||
}
|
Loading…
Add table
Reference in a new issue