mirror of
https://github.com/actix/examples
synced 2025-06-28 09:50:36 +02:00
upgrade example to actix-web 0.7
This commit is contained in:
@ -4,8 +4,10 @@ version = "0.1.0"
|
||||
authors = ["Darin Gordon <dkcdkg@gmail.com>"]
|
||||
|
||||
[dependencies]
|
||||
actix = "0.5"
|
||||
actix-web = "^0.6"
|
||||
actix = "0.7"
|
||||
#actix-web = "^0.7"
|
||||
actix-web = { git = "https://github.com/actix/actix-web.git" }
|
||||
|
||||
dotenv = "0.10"
|
||||
env_logger = "0.5"
|
||||
failure = "0.1.1"
|
||||
|
@ -1,31 +1,28 @@
|
||||
use actix::prelude::*;
|
||||
use std::{time::Duration, thread::sleep};
|
||||
use failure::Error;
|
||||
use r2d2;
|
||||
use r2d2_sqlite;
|
||||
|
||||
use std::{thread::sleep, time::Duration};
|
||||
|
||||
pub type Pool = r2d2::Pool<r2d2_sqlite::SqliteConnectionManager>;
|
||||
pub type Connection = r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>;
|
||||
|
||||
|
||||
pub struct DbExecutor(pub Pool);
|
||||
impl Actor for DbExecutor {
|
||||
type Context = SyncContext<Self>;
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum WeatherAgg {
|
||||
AnnualAgg {year: i32, total: f64},
|
||||
MonthAgg {year: i32, month: i32, total: f64}
|
||||
AnnualAgg { year: i32, total: f64 },
|
||||
MonthAgg { year: i32, month: i32, total: f64 },
|
||||
}
|
||||
|
||||
pub enum Queries {
|
||||
GetTopTenHottestYears,
|
||||
GetTopTenColdestYears,
|
||||
GetTopTenHottestMonths,
|
||||
GetTopTenColdestMonths
|
||||
GetTopTenColdestMonths,
|
||||
}
|
||||
|
||||
//pub struct GetTopTenHottestYears;
|
||||
@ -41,7 +38,7 @@ impl Handler<Queries> for DbExecutor {
|
||||
match msg {
|
||||
Queries::GetTopTenHottestYears => get_hottest_years(conn),
|
||||
Queries::GetTopTenColdestYears => get_coldest_years(conn),
|
||||
Queries::GetTopTenHottestMonths =>get_hottest_months(conn),
|
||||
Queries::GetTopTenHottestMonths => get_hottest_months(conn),
|
||||
Queries::GetTopTenColdestMonths => get_coldest_months(conn),
|
||||
}
|
||||
}
|
||||
@ -56,13 +53,17 @@ fn get_hottest_years(conn: Connection) -> Result<Vec<WeatherAgg>, Error> {
|
||||
GROUP BY theyear
|
||||
ORDER BY total DESC LIMIT 10;";
|
||||
|
||||
|
||||
let mut prep_stmt = conn.prepare(stmt)?;
|
||||
let annuals = prep_stmt.query_map(&[], |row| {
|
||||
WeatherAgg::AnnualAgg{year: row.get(0),
|
||||
total: row.get(1)}})
|
||||
.and_then(|mapped_rows|
|
||||
Ok(mapped_rows.map(|row| row.unwrap()).collect::<Vec<WeatherAgg>>()))?;
|
||||
let annuals = prep_stmt
|
||||
.query_map(&[], |row| WeatherAgg::AnnualAgg {
|
||||
year: row.get(0),
|
||||
total: row.get(1),
|
||||
})
|
||||
.and_then(|mapped_rows| {
|
||||
Ok(mapped_rows
|
||||
.map(|row| row.unwrap())
|
||||
.collect::<Vec<WeatherAgg>>())
|
||||
})?;
|
||||
|
||||
sleep(Duration::from_secs(2));
|
||||
|
||||
@ -79,11 +80,16 @@ fn get_coldest_years(conn: Connection) -> Result<Vec<WeatherAgg>, Error> {
|
||||
ORDER BY total ASC LIMIT 10;";
|
||||
|
||||
let mut prep_stmt = conn.prepare(stmt)?;
|
||||
let annuals = prep_stmt.query_map(&[], |row| {
|
||||
WeatherAgg::AnnualAgg{year: row.get(0),
|
||||
total: row.get(1)}})
|
||||
.and_then(|mapped_rows|
|
||||
Ok(mapped_rows.map(|row| row.unwrap()).collect::<Vec<WeatherAgg>>()))?;
|
||||
let annuals = prep_stmt
|
||||
.query_map(&[], |row| WeatherAgg::AnnualAgg {
|
||||
year: row.get(0),
|
||||
total: row.get(1),
|
||||
})
|
||||
.and_then(|mapped_rows| {
|
||||
Ok(mapped_rows
|
||||
.map(|row| row.unwrap())
|
||||
.collect::<Vec<WeatherAgg>>())
|
||||
})?;
|
||||
|
||||
sleep(Duration::from_secs(2));
|
||||
|
||||
@ -91,8 +97,7 @@ fn get_coldest_years(conn: Connection) -> Result<Vec<WeatherAgg>, Error> {
|
||||
}
|
||||
|
||||
fn get_hottest_months(conn: Connection) -> Result<Vec<WeatherAgg>, Error> {
|
||||
let stmt =
|
||||
"SELECT cast(strftime('%Y', date) as int) as theyear,
|
||||
let stmt = "SELECT cast(strftime('%Y', date) as int) as theyear,
|
||||
cast(strftime('%m', date) as int) as themonth,
|
||||
sum(tmax) as total
|
||||
FROM nyc_weather
|
||||
@ -101,20 +106,24 @@ fn get_hottest_months(conn: Connection) -> Result<Vec<WeatherAgg>, Error> {
|
||||
ORDER BY total DESC LIMIT 10;";
|
||||
|
||||
let mut prep_stmt = conn.prepare(stmt)?;
|
||||
let annuals = prep_stmt.query_map(&[], |row| {
|
||||
WeatherAgg::MonthAgg{year: row.get(0),
|
||||
month: row.get(1),
|
||||
total: row.get(2)}})
|
||||
.and_then(|mapped_rows|
|
||||
Ok(mapped_rows.map(|row| row.unwrap()).collect::<Vec<WeatherAgg>>()))?;
|
||||
let annuals = prep_stmt
|
||||
.query_map(&[], |row| WeatherAgg::MonthAgg {
|
||||
year: row.get(0),
|
||||
month: row.get(1),
|
||||
total: row.get(2),
|
||||
})
|
||||
.and_then(|mapped_rows| {
|
||||
Ok(mapped_rows
|
||||
.map(|row| row.unwrap())
|
||||
.collect::<Vec<WeatherAgg>>())
|
||||
})?;
|
||||
|
||||
sleep(Duration::from_secs(2));
|
||||
Ok(annuals)
|
||||
}
|
||||
|
||||
fn get_coldest_months(conn: Connection) -> Result<Vec<WeatherAgg>, Error> {
|
||||
let stmt =
|
||||
"SELECT cast(strftime('%Y', date) as int) as theyear,
|
||||
let stmt = "SELECT cast(strftime('%Y', date) as int) as theyear,
|
||||
cast(strftime('%m', date) as int) as themonth,
|
||||
sum(tmax) as total
|
||||
FROM nyc_weather
|
||||
@ -123,12 +132,17 @@ fn get_coldest_months(conn: Connection) -> Result<Vec<WeatherAgg>, Error> {
|
||||
ORDER BY total ASC LIMIT 10;";
|
||||
|
||||
let mut prep_stmt = conn.prepare(stmt)?;
|
||||
let annuals = prep_stmt.query_map(&[], |row| {
|
||||
WeatherAgg::MonthAgg{year: row.get(0),
|
||||
month: row.get(1),
|
||||
total: row.get(2)}})
|
||||
.and_then(|mapped_rows|
|
||||
Ok(mapped_rows.map(|row| row.unwrap()).collect::<Vec<WeatherAgg>>()))?;
|
||||
let annuals = prep_stmt
|
||||
.query_map(&[], |row| WeatherAgg::MonthAgg {
|
||||
year: row.get(0),
|
||||
month: row.get(1),
|
||||
total: row.get(2),
|
||||
})
|
||||
.and_then(|mapped_rows| {
|
||||
Ok(mapped_rows
|
||||
.map(|row| row.unwrap())
|
||||
.collect::<Vec<WeatherAgg>>())
|
||||
})?;
|
||||
|
||||
sleep(Duration::from_secs(2));
|
||||
Ok(annuals)
|
||||
|
@ -10,7 +10,7 @@ This project illustrates two examples:
|
||||
|
||||
*/
|
||||
|
||||
#[macro_use] extern crate actix;
|
||||
extern crate actix;
|
||||
extern crate actix_web;
|
||||
extern crate env_logger;
|
||||
extern crate failure;
|
||||
@ -19,51 +19,61 @@ extern crate num_cpus;
|
||||
extern crate r2d2;
|
||||
extern crate r2d2_sqlite;
|
||||
extern crate serde;
|
||||
#[macro_use] extern crate serde_derive;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
extern crate serde_json;
|
||||
|
||||
use actix::prelude::*;
|
||||
use actix_web::{
|
||||
http, middleware, server, App, AsyncResponder, FutureResponse, HttpResponse,
|
||||
State, Error as AWError
|
||||
http, middleware, server, App, AsyncResponder, Error as AWError, FutureResponse,
|
||||
HttpResponse, State,
|
||||
};
|
||||
use std::error::Error as StdError;
|
||||
use failure::Error;
|
||||
use futures::future::{Future, join_all, ok as fut_ok, err as fut_err};
|
||||
use futures::future::{join_all, ok as fut_ok, Future};
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
|
||||
mod db;
|
||||
use db::{DbExecutor, Queries, WeatherAgg, Pool};
|
||||
use db::{DbExecutor, Pool, Queries, WeatherAgg};
|
||||
|
||||
/// State with DbExecutor address
|
||||
struct AppState {
|
||||
db: Addr<Syn, DbExecutor>,
|
||||
db: Addr<DbExecutor>,
|
||||
}
|
||||
|
||||
|
||||
/// Version 1: Calls 4 queries in sequential order, as an asynchronous handler
|
||||
fn asyncio_weather(state: State<AppState>) -> FutureResponse<HttpResponse> {
|
||||
let mut result: Vec<Vec<WeatherAgg>> = vec![];
|
||||
|
||||
state.db.send(Queries::GetTopTenHottestYears).from_err()
|
||||
.and_then(move |res| {
|
||||
result.push(res.unwrap());
|
||||
state.db.send(Queries::GetTopTenColdestYears).from_err()
|
||||
state
|
||||
.db
|
||||
.send(Queries::GetTopTenHottestYears)
|
||||
.from_err()
|
||||
.and_then(move |res| {
|
||||
result.push(res.unwrap());
|
||||
state.db.send(Queries::GetTopTenHottestMonths).from_err()
|
||||
.and_then(move |res| {
|
||||
result.push(res.unwrap());
|
||||
state.db.send(Queries::GetTopTenColdestMonths).from_err()
|
||||
state
|
||||
.db
|
||||
.send(Queries::GetTopTenColdestYears)
|
||||
.from_err()
|
||||
.and_then(move |res| {
|
||||
result.push(res.unwrap());
|
||||
fut_ok(result)
|
||||
})
|
||||
})
|
||||
state
|
||||
.db
|
||||
.send(Queries::GetTopTenHottestMonths)
|
||||
.from_err()
|
||||
.and_then(move |res| {
|
||||
result.push(res.unwrap());
|
||||
state
|
||||
.db
|
||||
.send(Queries::GetTopTenColdestMonths)
|
||||
.from_err()
|
||||
.and_then(move |res| {
|
||||
result.push(res.unwrap());
|
||||
fut_ok(result)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
.and_then(|res| Ok(HttpResponse::Ok().json(res)))
|
||||
.responder()
|
||||
.and_then(|res| Ok(HttpResponse::Ok().json(res)))
|
||||
.responder()
|
||||
}
|
||||
|
||||
/// Version 2: Calls 4 queries in parallel, as an asynchronous handler
|
||||
@ -73,12 +83,13 @@ fn parallel_weather(state: State<AppState>) -> FutureResponse<HttpResponse> {
|
||||
Box::new(state.db.send(Queries::GetTopTenHottestYears)),
|
||||
Box::new(state.db.send(Queries::GetTopTenColdestYears)),
|
||||
Box::new(state.db.send(Queries::GetTopTenHottestMonths)),
|
||||
Box::new(state.db.send(Queries::GetTopTenColdestMonths))];
|
||||
Box::new(state.db.send(Queries::GetTopTenColdestMonths)),
|
||||
];
|
||||
|
||||
join_all(fut_result)
|
||||
.map_err(AWError::from)
|
||||
.and_then(|result| {
|
||||
let res: Vec<Option<Vec<WeatherAgg>>> =
|
||||
let res: Vec<Option<Vec<WeatherAgg>>> =
|
||||
result.into_iter().map(|x| x.ok()).collect();
|
||||
|
||||
Ok(HttpResponse::Ok().json(res))
|
||||
@ -103,10 +114,10 @@ fn main() {
|
||||
App::with_state(AppState{db: addr.clone()})
|
||||
// enable logger
|
||||
.middleware(middleware::Logger::default())
|
||||
.resource("/asyncio_weather", |r|
|
||||
.resource("/asyncio_weather", |r|
|
||||
r.method(http::Method::GET)
|
||||
.with(asyncio_weather))
|
||||
.resource("/parallel_weather", |r|
|
||||
.resource("/parallel_weather", |r|
|
||||
r.method(http::Method::GET)
|
||||
.with(parallel_weather))
|
||||
}).bind("127.0.0.1:8080")
|
||||
|
Reference in New Issue
Block a user