mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-25 01:51:23 +02:00
add graceful shutdown system
This commit is contained in:
@ -164,3 +164,73 @@ fn index(req: HttpRequest) -> HttpResponse {
|
||||
}
|
||||
# fn main() {}
|
||||
```
|
||||
|
||||
## Graceful shutdown
|
||||
|
||||
Actix http server support graceful shutdown. After receiving a stop signal, workers
|
||||
have specific amount of time to finish serving requests. Workers still alive after the
|
||||
timeout are force dropped. By default shutdown timeout sets to 30 seconds.
|
||||
You can change this parameter with `HttpServer::shutdown_timeout()` method.
|
||||
|
||||
You can send stop message to server with server address and specify if you what
|
||||
graceful shutdown or not. `start()` or `spawn()` methods return address of the server.
|
||||
|
||||
```rust
|
||||
# extern crate futures;
|
||||
# extern crate actix;
|
||||
# extern crate actix_web;
|
||||
# use futures::Future;
|
||||
use actix_web::*;
|
||||
|
||||
fn main() {
|
||||
let addr = HttpServer::new(
|
||||
|| Application::new()
|
||||
.resource("/", |r| r.h(httpcodes::HTTPOk)))
|
||||
.bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
|
||||
.shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds
|
||||
.spawn();
|
||||
|
||||
let _ = addr.call_fut(
|
||||
dev::StopServer{graceful:true}).wait(); // <- Send `StopServer` message to server.
|
||||
}
|
||||
```
|
||||
|
||||
It is possible to use unix signals on compatible OSs. "signal" feature needs to be enabled
|
||||
in *Cargo.toml* for *actix-web* dependency.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] }
|
||||
```
|
||||
|
||||
Then you can subscribe your server to unix signals. Http server handles three signals:
|
||||
|
||||
* *SIGINT* - Force shutdown workers
|
||||
* *SIGTERM* - Graceful shutdown workers
|
||||
* *SIGQUIT* - Force shutdown workers
|
||||
|
||||
```rust,ignore
|
||||
# extern crate futures;
|
||||
# extern crate actix;
|
||||
# extern crate actix_web;
|
||||
use actix_web::*;
|
||||
use actix::actors::signal::{ProcessSignals, Subscribe};
|
||||
|
||||
fn main() {
|
||||
let sys = actix::System::new("signals");
|
||||
|
||||
let addr = HttpServer::new(|| {
|
||||
Application::new()
|
||||
.resource("/", |r| r.h(httpcodes::HTTPOk))})
|
||||
.bind("127.0.0.1:8080").unwrap()
|
||||
.start();
|
||||
|
||||
// Subscribe to unix signals
|
||||
let signals = Arbiter::system_registry().get::<ProcessSignals>();
|
||||
signals.send(Subscribe(addr.subscriber()));
|
||||
|
||||
println!("Started http server: 127.0.0.1:8080");
|
||||
# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
|
||||
let _ = sys.run();
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user