Created
January 11, 2021 23:16
-
-
Save kppullin/6f3b40d336a22571a7c5413721ca38a1 to your computer and use it in GitHub Desktop.
actix app data - avoiding double arc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "actix-data--no-double-arc" | |
version = "0.1.0" | |
edition = "2018" | |
[dependencies] | |
actix-rt = "1.1.1" | |
actix-web = { version = "3.3.2" } | |
futures = "0.3.8" | |
tokio = { version = "0.2.24", features = ["macros"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use actix_web::{ | |
dev::Payload, post, App, Error, FromRequest, HttpRequest, HttpResponse, HttpServer, Responder, | |
}; | |
use futures::future::{ok, Ready}; | |
use std::sync::{Arc, Mutex}; | |
use std::time::{SystemTime, UNIX_EPOCH}; | |
use tokio::time::Duration; | |
#[derive(Clone)] | |
struct Timestamps { | |
data: Arc<Mutex<Vec<u64>>>, | |
start_time: u64, | |
} | |
impl Timestamps { | |
fn new() -> Timestamps { | |
Timestamps { | |
data: Arc::new(Mutex::new(Vec::new())), | |
start_time: SystemTime::now() | |
.duration_since(UNIX_EPOCH) | |
.unwrap() | |
.as_secs(), | |
} | |
} | |
fn insert_timestamp(&self) { | |
self.data.lock().unwrap().push( | |
SystemTime::now() | |
.duration_since(UNIX_EPOCH) | |
.unwrap() | |
.as_secs(), | |
); | |
} | |
fn run_poller(timestamps: Timestamps) { | |
tokio::spawn(async move { | |
loop { | |
timestamps.insert_timestamp(); | |
tokio::time::delay_for(Duration::from_secs(10)).await; | |
} | |
}); | |
} | |
} | |
impl FromRequest for Timestamps { | |
type Error = Error; | |
type Future = Ready<Result<Self, Self::Error>>; | |
type Config = (); | |
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { | |
ok(req.app_data::<Timestamps>().unwrap().clone()) | |
} | |
} | |
#[post("/insert_timestamp")] | |
async fn insert_timestamp(timestamps: Option<Timestamps>) -> impl Responder { | |
{ | |
println!("{:?}", timestamps.clone().unwrap().data.lock().unwrap()); | |
} | |
timestamps.unwrap().insert_timestamp(); | |
HttpResponse::Ok() | |
} | |
#[actix_rt::main] | |
async fn main() -> std::io::Result<()> { | |
let timestamps = Timestamps::new(); | |
Timestamps::run_poller(timestamps.clone()); | |
let _ = HttpServer::new(move || { | |
App::new() | |
.app_data(timestamps.clone()) | |
.service(insert_timestamp) | |
}) | |
.workers(4) | |
.bind("0.0.0.0:8000") | |
.unwrap() | |
.run() | |
.await; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment