1
0
mirror of https://github.com/actix/examples synced 2024-11-28 00:12:57 +01:00
examples/state/src/main.rs

79 lines
2.8 KiB
Rust
Raw Normal View History

2019-03-17 04:23:09 +01:00
//! Application may have multiple data objects that are shared across
//! all handlers within same Application.
2018-05-02 15:20:43 +02:00
//!
//! For global shared state, we wrap our state in a `actix_web::web::Data` and move it into
//! the factory closure. The closure is called once-per-thread, and we clone our state
//! and attach to each instance of the `App` with `.app_data(state.clone())`.
//!
//! For thread-local state, we construct our state within the factory closure and attach to
//! the app with `.data(state)`.
//!
//! We retrieve our app state within our handlers with a `state: Data<...>` argument.
//!
//! By default, `actix-web` runs one `App` per logical cpu core.
//! When running on <N> cores, we see that the example will increment `counter1` (global state via
//! Mutex) and `counter3` (global state via Atomic variable) each time the endpoint is called,
//! but only appear to increment `counter2` every Nth time on average (thread-local state). This
//! is because the workload is being shared equally among cores.
2018-05-02 15:20:43 +02:00
//!
2019-11-14 21:16:48 +01:00
//! Check [user guide](https://actix.rs/docs/application/#state) for more info.
use std::cell::Cell;
2019-03-07 23:50:29 +01:00
use std::io;
use std::sync::atomic::{AtomicUsize, Ordering};
2019-06-06 12:47:40 +02:00
use std::sync::Mutex;
2019-03-07 23:50:29 +01:00
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
/// simple handle
async fn index(
counter1: web::Data<Mutex<usize>>,
counter2: web::Data<Cell<u32>>,
counter3: web::Data<AtomicUsize>,
req: HttpRequest,
) -> HttpResponse {
println!("{:?}", req);
// Increment the counters
*counter1.lock().unwrap() += 1;
counter2.set(counter2.get() + 1);
counter3.fetch_add(1, Ordering::SeqCst);
let body = format!(
"global mutex counter: {}, local counter: {}, global atomic counter: {}",
*counter1.lock().unwrap(),
counter2.get(),
counter3.load(Ordering::SeqCst),
);
HttpResponse::Ok().body(body)
}
2019-12-07 18:59:24 +01:00
#[actix_rt::main]
async fn main() -> io::Result<()> {
2019-03-07 23:50:29 +01:00
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
// Create some global state prior to building the server
2020-04-03 09:14:30 +02:00
#[allow(clippy::mutex_atomic)] // it's intentional.
let counter1 = web::Data::new(Mutex::new(0usize));
let counter3 = web::Data::new(AtomicUsize::new(0usize));
2019-03-07 23:50:29 +01:00
// move is necessary to give closure below ownership of counter1
2019-03-07 23:50:29 +01:00
HttpServer::new(move || {
// Create some thread-local state
let counter2 = Cell::new(0u32);
2019-03-07 23:50:29 +01:00
App::new()
.app_data(counter1.clone()) // add shared state
.app_data(counter3.clone()) // add shared state
.data(counter2) // add thread-local state
// enable logger
2019-03-26 04:29:00 +01:00
.wrap(middleware::Logger::default())
// register simple handler
2019-03-07 23:50:29 +01:00
.service(web::resource("/").to(index))
})
.bind("127.0.0.1:8080")?
2019-12-25 17:48:33 +01:00
.run()
2019-12-07 18:59:24 +01:00
.await
}