From 67f33a4760d295d8db059da5945e8f1f4fb66464 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Wed, 28 Feb 2018 10:26:40 -0800 Subject: [PATCH] add redis session example --- Cargo.toml | 1 + examples/redis-session/Cargo.toml | 11 +++++++ examples/redis-session/src/main.rs | 48 ++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 examples/redis-session/Cargo.toml create mode 100644 examples/redis-session/src/main.rs diff --git a/Cargo.toml b/Cargo.toml index 3d12d1388..0780053d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -108,6 +108,7 @@ members = [ "examples/hello-world", "examples/multipart", "examples/state", + "examples/redis-session", "examples/template_tera", "examples/tls", "examples/websocket", diff --git a/examples/redis-session/Cargo.toml b/examples/redis-session/Cargo.toml new file mode 100644 index 000000000..cfa102d11 --- /dev/null +++ b/examples/redis-session/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "redis-session" +version = "0.1.0" +authors = ["Nikolay Kim "] +workspace = "../.." + +[dependencies] +env_logger = "0.5" +actix = "0.5" +actix-web = "0.4" +actix-redis = { version = "0.2", features = ["web"] } diff --git a/examples/redis-session/src/main.rs b/examples/redis-session/src/main.rs new file mode 100644 index 000000000..36df16559 --- /dev/null +++ b/examples/redis-session/src/main.rs @@ -0,0 +1,48 @@ +#![allow(unused_variables)] + +extern crate actix; +extern crate actix_web; +extern crate actix_redis; +extern crate env_logger; + +use actix_web::*; +use actix_web::middleware::RequestSession; +use actix_redis::RedisSessionBackend; + + +/// simple handler +fn index(mut req: HttpRequest) -> Result { + println!("{:?}", req); + + // session + if let Some(count) = req.session().get::("counter")? { + println!("SESSION value: {}", count); + req.session().set("counter", count+1)?; + } else { + req.session().set("counter", 1)?; + } + + Ok("Welcome!".into()) +} + +fn main() { + ::std::env::set_var("RUST_LOG", "actix_web=info,actix_redis=info"); + env_logger::init(); + let sys = actix::System::new("basic-example"); + + HttpServer::new( + || Application::new() + // enable logger + .middleware(middleware::Logger::default()) + // cookie session middleware + .middleware(middleware::SessionStorage::new( + RedisSessionBackend::new("127.0.0.1:6379", &[0; 32]) + )) + // register simple route, handle all methods + .resource("/", |r| r.f(index))) + .bind("0.0.0.0:8080").unwrap() + .threads(1) + .start(); + + let _ = sys.run(); +}