mirror of
https://github.com/actix/examples
synced 2024-11-23 14:31:07 +01:00
add run-in-thread example
This commit is contained in:
parent
01b0d5fb21
commit
a0812c9b29
@ -23,6 +23,7 @@ members = [
|
||||
"r2d2",
|
||||
"redis",
|
||||
"redis-session",
|
||||
"run-in-thread",
|
||||
"rustls",
|
||||
"server-sent-events",
|
||||
"simple-auth-server",
|
||||
|
11
run-in-thread/Cargo.toml
Normal file
11
run-in-thread/Cargo.toml
Normal file
@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "run-in-thread"
|
||||
version = "2.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
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"
|
52
run-in-thread/src/main.rs
Normal file
52
run-in-thread/src/main.rs
Normal file
@ -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<Server>) -> 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));
|
||||
}
|
Loading…
Reference in New Issue
Block a user