1
0
mirror of https://github.com/actix/examples synced 2025-06-28 09:50:36 +02:00

fix db/basic

This commit is contained in:
Rob Ede
2022-02-06 08:19:35 +00:00
parent 8ae47c8cda
commit a4d43c0ff8
12 changed files with 112 additions and 103 deletions

View File

@ -0,0 +1,2 @@
weather.db
weather.db-*

View File

@ -4,13 +4,13 @@ version = "1.0.0"
edition = "2021"
[dependencies]
actix-web = "4.0.0-rc.1"
env_logger = "0.9.0"
failure = "0.1.7"
futures = "0.3.1"
num_cpus = "1.13"
r2d2 = "0.8.2"
r2d2_sqlite = "0.18.0"
rusqlite = "0.25.4"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
actix-web = "4.0.0-rc.2"
env_logger = "0.9"
futures-util = { version = "0.3", default-features = false, features = ["std"] }
log = "0.4"
r2d2 = "0.8"
r2d2_sqlite = "0.19"
rusqlite = "0.26"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

View File

@ -1,5 +1,4 @@
use actix_web::{error::InternalError, http::StatusCode, web};
use failure::Error;
use actix_web::{error, web, Error};
use rusqlite::Statement;
use serde::{Deserialize, Serialize};
use std::{thread::sleep, time::Duration};
@ -22,26 +21,26 @@ pub enum Queries {
GetTopTenColdestMonths,
}
pub async fn execute(
pool: &Pool,
query: Queries,
) -> Result<Vec<WeatherAgg>, InternalError<Error>> {
pub async fn execute(pool: &Pool, query: Queries) -> Result<Vec<WeatherAgg>, Error> {
let pool = pool.clone();
let conn = web::block(move || pool.get())
.await?
.map_err(error::ErrorInternalServerError)?;
web::block(move || {
// simulate an expensive query, see comments at top of main.rs
sleep(Duration::from_secs(2));
let result = match query {
Queries::GetTopTenHottestYears => get_hottest_years(pool.get()?),
Queries::GetTopTenColdestYears => get_coldest_years(pool.get()?),
Queries::GetTopTenHottestMonths => get_hottest_months(pool.get()?),
Queries::GetTopTenColdestMonths => get_coldest_months(pool.get()?),
};
result.map_err(Error::from)
match query {
Queries::GetTopTenHottestYears => get_hottest_years(conn),
Queries::GetTopTenColdestYears => get_coldest_years(conn),
Queries::GetTopTenHottestMonths => get_hottest_months(conn),
Queries::GetTopTenColdestMonths => get_coldest_months(conn),
}
})
.await
.unwrap()
.map_err(|e| InternalError::new(e, StatusCode::INTERNAL_SERVER_ERROR))
.await?
.map_err(error::ErrorInternalServerError)
}
fn get_hottest_years(conn: Connection) -> WeatherAggResult {

View File

@ -1,28 +1,27 @@
/* Actix-Web Asynchronous Database Example
//! Actix Web Asynchronous Database Example
//!
//! This project illustrates expensive and blocking database requests that runs
//! in a thread-pool using `web::block` with two examples:
//!
//! 1. An asynchronous handler that executes 4 queries in *sequential order*,
//! collecting the results and returning them as a single serialized json object
//!
//! 2. An asynchronous handler that executes 4 queries in *parallel*,
//! collecting the results and returning them as a single serialized json object
//!
//! Note: The use of sleep(Duration::from_secs(2)); in db.rs is to make performance
//! improvement with parallelism more obvious.
This project illustrates expensive and blocking database requests that runs
in a thread-pool using `web::block` with two examples:
1. An asynchronous handler that executes 4 queries in *sequential order*,
collecting the results and returning them as a single serialized json object
2. An asynchronous handler that executes 4 queries in *parallel*,
collecting the results and returning them as a single serialized json object
Note: The use of sleep(Duration::from_secs(2)); in db.rs is to make performance
improvement with parallelism more obvious.
*/
use std::io;
use actix_web::{middleware, web, App, Error as AWError, HttpResponse, HttpServer};
use futures::future::join_all;
use futures_util::future::join_all;
use r2d2_sqlite::{self, SqliteConnectionManager};
mod db;
use db::{Pool, Queries};
/// Version 1: Calls 4 queries in sequential order, as an asynchronous handler
#[allow(clippy::eval_order_dependence)] // it's FP?
async fn asyncio_weather(db: web::Data<Pool>) -> Result<HttpResponse, AWError> {
let result = vec![
db::execute(&db, Queries::GetTopTenHottestYears).await?,
@ -50,14 +49,15 @@ async fn parallel_weather(db: web::Data<Pool>) -> Result<HttpResponse, AWError>
#[actix_web::main]
async fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
// Start N db executor actors (N = number of cores avail)
// connect to SQLite DB
let manager = SqliteConnectionManager::file("weather.db");
let pool = Pool::new(manager).unwrap();
// Start http server
log::info!("starting HTTP server at http://localhost:8080");
// start HTTP server
HttpServer::new(move || {
App::new()
// store db pool as Data object
@ -71,7 +71,8 @@ async fn main() -> io::Result<()> {
.route(web::get().to(parallel_weather)),
)
})
.bind("127.0.0.1:8080")?
.bind(("127.0.0.1", 8080))?
.workers(2)
.run()
.await
}