1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 09:42:40 +01:00
actix-extras/guide/src/qs_3_5.md

211 lines
6.8 KiB
Markdown
Raw Normal View History

2017-12-14 06:44:16 +01:00
# Server
The [**HttpServer**](../actix_web/server/struct.HttpServer.html) type is responsible for
2018-04-06 02:55:19 +02:00
serving http requests.
`HttpServer` accepts an application factory as a parameter, and the
application factory must have `Send` + `Sync` boundaries. More about that in the
*multi-threading* section.
To bind to a specific socket address, `bind()` must be used, and it may be called multiple times.
To start the http server, one of the start methods.
- use `start()` for a simple server
- use `start_tls()` or `start_ssl()` for a ssl server
`HttpServer` is an actix actor. It must be initialized within a properly configured actix system:
2017-12-19 03:56:58 +01:00
```rust
# extern crate actix;
# extern crate actix_web;
use actix_web::{server::HttpServer, App, HttpResponse};
2017-12-19 03:56:58 +01:00
fn main() {
let sys = actix::System::new("guide");
HttpServer::new(
2018-03-31 09:16:55 +02:00
|| App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
2017-12-19 03:56:58 +01:00
.bind("127.0.0.1:59080").unwrap()
2017-12-19 18:08:36 +01:00
.start();
2017-12-19 03:56:58 +01:00
2018-02-13 07:56:47 +01:00
# actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
2017-12-19 03:56:58 +01:00
let _ = sys.run();
}
```
2017-12-14 07:36:28 +01:00
2018-04-06 02:55:19 +02:00
> It is possible to start a server in a separate thread with the `spawn()` method. In that
> case the server spawns a new thread and creates a new actix system in it. To stop
> this server, send a `StopServer` message.
2017-12-28 02:49:10 +01:00
2018-04-06 02:55:19 +02:00
`HttpServer` is implemented as an actix actor. It is possible to communicate with the server
via a messaging system. All start methods, e.g. `start()` and `start_ssl()`, return the
address of the started http server. It accepts several messages:
2017-12-28 02:49:10 +01:00
2018-04-06 02:55:19 +02:00
- `PauseServer` - Pause accepting incoming connections
- `ResumeServer` - Resume accepting incoming connections
- `StopServer` - Stop incoming connection processing, stop all workers and exit
2017-12-28 02:49:10 +01:00
```rust
# extern crate futures;
# extern crate actix;
# extern crate actix_web;
# use futures::Future;
2018-01-06 01:32:36 +01:00
use std::thread;
use std::sync::mpsc;
use actix_web::{server, App, HttpResponse};
2017-12-28 02:49:10 +01:00
fn main() {
2018-01-06 01:32:36 +01:00
let (tx, rx) = mpsc::channel();
2018-02-13 07:56:47 +01:00
2018-01-06 01:32:36 +01:00
thread::spawn(move || {
let sys = actix::System::new("http-server");
let addr = server::new(
2018-03-31 09:16:55 +02:00
|| App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
2018-01-06 01:32:36 +01:00
.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
.start();
let _ = tx.send(addr);
let _ = sys.run();
});
let addr = rx.recv().unwrap();
2018-02-13 07:56:47 +01:00
let _ = addr.send(
2018-01-12 03:35:05 +01:00
server::StopServer{graceful:true}).wait(); // <- Send `StopServer` message to server.
2017-12-28 02:49:10 +01:00
}
```
2017-12-18 22:06:41 +01:00
2017-12-14 06:44:16 +01:00
## Multi-threading
2018-04-06 02:55:19 +02:00
`HttpServer` automatically starts an number of http workers, by default
2018-03-28 22:16:01 +02:00
this number is equal to number of logical CPUs in the system. This number
can be overridden with the `HttpServer::threads()` method.
2017-12-14 06:44:16 +01:00
```rust
# extern crate actix_web;
# extern crate tokio_core;
use actix_web::{App, HttpResponse, server::HttpServer};
2017-12-14 06:44:16 +01:00
fn main() {
2018-02-10 20:01:54 +01:00
HttpServer::new(
2018-03-31 09:16:55 +02:00
|| App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
2017-12-20 03:44:17 +01:00
.threads(4); // <- Start 4 workers
2017-12-14 06:44:16 +01:00
}
```
2018-03-28 22:16:01 +02:00
The server creates a separate application instance for each created worker. Application state
2018-04-06 02:55:19 +02:00
is not shared between threads. To share state, `Arc` could be used.
> Application state does not need to be `Send` and `Sync`,
> but factories must be `Send` + `Sync`.
2017-12-14 06:44:16 +01:00
2017-12-14 06:56:30 +01:00
## SSL
2018-03-28 22:16:01 +02:00
There are two features for ssl server: `tls` and `alpn`. The `tls` feature is for `native-tls`
2017-12-14 06:56:30 +01:00
integration and `alpn` is for `openssl`.
```toml
[dependencies]
actix-web = { git = "https://github.com/actix/actix-web", features=["alpn"] }
```
```rust,ignore
use std::fs::File;
use actix_web::*;
fn main() {
// load ssl keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();
2017-12-14 06:56:30 +01:00
server::new(
2018-03-31 09:16:55 +02:00
|| App::new()
2017-12-14 06:56:30 +01:00
.resource("/index.html", |r| r.f(index)))
2017-12-19 18:08:36 +01:00
.bind("127.0.0.1:8080").unwrap()
.serve_ssl(builder).unwrap();
2017-12-14 06:56:30 +01:00
}
```
2018-04-06 02:55:19 +02:00
> **Note**: the *HTTP/2.0* protocol requires
> [tls alpn](https://tools.ietf.org/html/rfc7301).
> At the moment, only `openssl` has `alpn` support.
> For a full example, check out
> [examples/tls](https://github.com/actix/actix-web/tree/master/examples/tls).
2017-12-14 06:56:30 +01:00
2017-12-14 06:44:16 +01:00
## Keep-Alive
2018-04-06 02:55:19 +02:00
Actix can wait for requests on a keep-alive connection.
2017-12-14 06:44:16 +01:00
2018-04-06 02:55:19 +02:00
> *keep alive* connection behavior is defined by server settings.
- `75`, `Some(75)`, `KeepAlive::Timeout(75)` - enable 75 second *keep alive* timer.
- `None` or `KeepAlive::Disabled` - disable *keep alive*.
- `KeepAlive::Tcp(75)` - use `SO_KEEPALIVE` socket option.
2017-12-14 06:44:16 +01:00
```rust
# extern crate actix_web;
# extern crate tokio_core;
2018-03-31 09:16:55 +02:00
use actix_web::{server, App, HttpResponse};
2017-12-14 06:44:16 +01:00
fn main() {
server::new(||
2018-03-31 09:16:55 +02:00
App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(75); // <- Set keep-alive to 75 seconds
server::new(||
2018-03-31 09:16:55 +02:00
App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
2018-03-10 06:40:51 +01:00
.keep_alive(server::KeepAlive::Tcp(75)); // <- Use `SO_KEEPALIVE` socket option.
server::new(||
2018-03-31 09:16:55 +02:00
App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(None); // <- Disable keep-alive
2017-12-14 06:44:16 +01:00
}
```
2018-04-06 02:55:19 +02:00
If the first option is selected, then *keep alive* state is
2018-03-28 22:16:01 +02:00
calculated based on the response's *connection-type*. By default
2018-04-06 02:55:19 +02:00
`HttpResponse::connection_type` is not defined. In that case *keep alive* is
defined by the request's http version.
> *keep alive* is **off** for *HTTP/1.0* and is **on** for *HTTP/1.1* and *HTTP/2.0*.
2017-12-14 06:44:16 +01:00
2018-03-28 22:16:01 +02:00
*Connection type* can be change with `HttpResponseBuilder::connection_type()` method.
2017-12-14 06:44:16 +01:00
```rust
# extern crate actix_web;
use actix_web::{HttpRequest, HttpResponse, http};
2017-12-14 06:44:16 +01:00
fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
2018-03-31 02:31:18 +02:00
.connection_type(http::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method
.finish()
2017-12-14 06:44:16 +01:00
}
# fn main() {}
```
2017-12-29 01:25:47 +01:00
## Graceful shutdown
2018-04-06 02:55:19 +02:00
`HttpServer` supports graceful shutdown. After receiving a stop signal, workers
have a specific amount of time to finish serving requests. Any workers still alive after the
2018-03-28 22:16:01 +02:00
timeout are force-dropped. By default the shutdown timeout is set to 30 seconds.
You can change this parameter with the `HttpServer::shutdown_timeout()` method.
2017-12-29 01:25:47 +01:00
2018-03-28 22:16:01 +02:00
You can send a stop message to the server with the server address and specify if you want
2018-04-06 02:55:19 +02:00
graceful shutdown or not. The `start()` methods returns address of the server.
2017-12-29 01:25:47 +01:00
2018-04-06 02:55:19 +02:00
`HttpServer` handles several OS signals. *CTRL-C* is available on all OSs,
2018-01-06 01:32:36 +01:00
other signals are available on unix systems.
2017-12-29 01:25:47 +01:00
2018-04-06 02:55:19 +02:00
- *SIGINT* - Force shutdown workers
- *SIGTERM* - Graceful shutdown workers
- *SIGQUIT* - Force shutdown workers
2017-12-29 01:25:47 +01:00
2018-04-06 02:55:19 +02:00
> It is possible to disable signal handling with `HttpServer::disable_signals()` method.