diff --git a/Cargo.toml b/Cargo.toml index 2366cf7..09df84b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ members = [ "r2d2", "redis", "redis-session", + "run-in-thread", "rustls", "server-sent-events", "simple-auth-server", diff --git a/run-in-thread/Cargo.toml b/run-in-thread/Cargo.toml new file mode 100644 index 0000000..2c6d964 --- /dev/null +++ b/run-in-thread/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "run-in-thread" +version = "2.0.0" +authors = ["Nikolay Kim "] +edition = "2018" +description = "Run actix-web in separate thread" + +[dependencies] +actix-web = "2.0.0-rc" +actix-rt = "1.0.0" +env_logger = "0.6" \ No newline at end of file diff --git a/run-in-thread/src/main.rs b/run-in-thread/src/main.rs new file mode 100644 index 0000000..8ade190 --- /dev/null +++ b/run-in-thread/src/main.rs @@ -0,0 +1,52 @@ +use std::sync::mpsc; +use std::{thread, time}; + +use actix_rt::System; +use actix_web::{dev::Server, middleware, web, App, HttpRequest, HttpServer}; + +async fn index(req: HttpRequest) -> &'static str { + println!("REQ: {:?}", req); + "Hello world!" +} + +fn run_app(tx: mpsc::Sender) -> std::io::Result<()> { + let mut sys = System::new("test"); + + // srv is server controller type, `dev::Server` + let srv = HttpServer::new(|| { + App::new() + // enable logger + .wrap(middleware::Logger::default()) + .service(web::resource("/index.html").to(|| async { "Hello world!" })) + .service(web::resource("/").to(index)) + }) + .bind("127.0.0.1:8080")? + .start(); + + // send server controller to main thread + let _ = tx.send(srv.clone()); + + // run future + sys.block_on(srv) +} + +fn main() { + std::env::set_var("RUST_LOG", "actix_web=info,actix_server=trace"); + env_logger::init(); + + let (tx, rx) = mpsc::channel(); + + println!("START SERVER"); + thread::spawn(move || { + let _ = run_app(tx); + }); + + let srv = rx.recv().unwrap(); + + println!("WATING 10 SECONDS"); + thread::sleep(time::Duration::from_secs(10)); + + println!("STOPPING SERVER"); + // init stop server and wait until server gracefully exit + System::new("").block_on(srv.stop(true)); +}