mirror of
https://github.com/actix/examples
synced 2024-11-30 17:14:35 +01:00
convert r2d2 example
This commit is contained in:
parent
40b5498902
commit
10731e43c6
@ -7,7 +7,6 @@ edition = "2018"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-rt = "0.1"
|
actix-rt = "0.1"
|
||||||
|
|
||||||
actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
|
actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
|
||||||
actix-session = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
|
actix-session = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
|
||||||
actix-staticfiles = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
|
actix-staticfiles = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
|
||||||
|
@ -2,20 +2,17 @@
|
|||||||
name = "r2d2-example"
|
name = "r2d2-example"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
|
edition = "2018"
|
||||||
workspace = "../"
|
workspace = "../"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
env_logger = "0.5"
|
actix-rt = "0.1"
|
||||||
|
actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
|
||||||
actix = "0.7"
|
|
||||||
actix-web = "0.7"
|
|
||||||
|
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
uuid = { version = "0.5", features = ["serde", "v4"] }
|
env_logger = "0.6"
|
||||||
serde = "1.0"
|
uuid = { version = "0.7", features = ["v4"] }
|
||||||
serde_json = "1.0"
|
|
||||||
serde_derive = "1.0"
|
|
||||||
|
|
||||||
r2d2 = "*"
|
r2d2 = "0.8"
|
||||||
r2d2_sqlite = "*"
|
r2d2_sqlite = "0.8"
|
||||||
rusqlite = "*"
|
rusqlite = "0.16"
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
//! Db executor actor
|
|
||||||
use actix::prelude::*;
|
|
||||||
use actix_web::*;
|
|
||||||
use r2d2::Pool;
|
|
||||||
use r2d2_sqlite::SqliteConnectionManager;
|
|
||||||
use std::io;
|
|
||||||
use uuid;
|
|
||||||
|
|
||||||
/// This is db executor actor. We are going to run 3 of them in parallel.
|
|
||||||
pub struct DbExecutor(pub Pool<SqliteConnectionManager>);
|
|
||||||
|
|
||||||
/// This is only message that this actor can handle, but it is easy to extend
|
|
||||||
/// number of messages.
|
|
||||||
pub struct CreateUser {
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Message for CreateUser {
|
|
||||||
type Result = Result<String, io::Error>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Actor for DbExecutor {
|
|
||||||
type Context = SyncContext<Self>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Handler<CreateUser> for DbExecutor {
|
|
||||||
type Result = Result<String, io::Error>;
|
|
||||||
|
|
||||||
fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result {
|
|
||||||
let conn = self.0.get().unwrap();
|
|
||||||
|
|
||||||
let uuid = format!("{}", uuid::Uuid::new_v4());
|
|
||||||
conn.execute(
|
|
||||||
"INSERT INTO users (id, name) VALUES ($1, $2)",
|
|
||||||
&[&uuid, &msg.name],
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
Ok(conn
|
|
||||||
.query_row("SELECT name FROM users WHERE id=$1", &[&uuid], |row| {
|
|
||||||
row.get(0)
|
|
||||||
})
|
|
||||||
.map_err(|_| io::Error::new(io::ErrorKind::Other, "db error"))?)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,68 +1,58 @@
|
|||||||
//! Actix web r2d2 example
|
//! Actix web r2d2 example
|
||||||
extern crate actix;
|
use std::io;
|
||||||
extern crate actix_web;
|
|
||||||
extern crate env_logger;
|
|
||||||
extern crate futures;
|
|
||||||
extern crate r2d2;
|
|
||||||
extern crate r2d2_sqlite;
|
|
||||||
extern crate rusqlite;
|
|
||||||
extern crate serde;
|
|
||||||
extern crate serde_json;
|
|
||||||
extern crate uuid;
|
|
||||||
|
|
||||||
use actix::prelude::*;
|
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
http, middleware, server, App, AsyncResponder, Error, HttpRequest, HttpResponse,
|
blocking, extract::Path, web, App, Error, HttpResponse, HttpServer, State,
|
||||||
};
|
};
|
||||||
use futures::future::Future;
|
use futures::Future;
|
||||||
|
use r2d2::Pool;
|
||||||
use r2d2_sqlite::SqliteConnectionManager;
|
use r2d2_sqlite::SqliteConnectionManager;
|
||||||
|
use uuid;
|
||||||
|
|
||||||
mod db;
|
/// Async request handler. Ddb pool is stored in application state.
|
||||||
use db::{CreateUser, DbExecutor};
|
fn index(
|
||||||
|
path: Path<String>,
|
||||||
|
db: State<Pool<SqliteConnectionManager>>,
|
||||||
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
|
// execute sync code in threadpool
|
||||||
|
blocking::run(move || {
|
||||||
|
let conn = db.get().unwrap();
|
||||||
|
|
||||||
/// State with DbExecutor address
|
let uuid = format!("{}", uuid::Uuid::new_v4());
|
||||||
struct State {
|
conn.execute(
|
||||||
db: Addr<DbExecutor>,
|
"INSERT INTO users (id, name) VALUES ($1, $2)",
|
||||||
|
&[&uuid, &path.into_inner()],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
conn.query_row("SELECT name FROM users WHERE id=$1", &[&uuid], |row| {
|
||||||
|
row.get::<_, String>(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.then(|res| match res {
|
||||||
|
Ok(user) => Ok(HttpResponse::Ok().json(user)),
|
||||||
|
Err(_) => Ok(HttpResponse::InternalServerError().into()),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Async request handler
|
fn main() -> io::Result<()> {
|
||||||
fn index(req: &HttpRequest<State>) -> Box<Future<Item = HttpResponse, Error = Error>> {
|
std::env::set_var("RUST_LOG", "actix_web=debug");
|
||||||
let name = &req.match_info()["name"];
|
|
||||||
|
|
||||||
req.state()
|
|
||||||
.db
|
|
||||||
.send(CreateUser {
|
|
||||||
name: name.to_owned(),
|
|
||||||
})
|
|
||||||
.from_err()
|
|
||||||
.and_then(|res| match res {
|
|
||||||
Ok(user) => Ok(HttpResponse::Ok().json(user)),
|
|
||||||
Err(_) => Ok(HttpResponse::InternalServerError().into()),
|
|
||||||
})
|
|
||||||
.responder()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
::std::env::set_var("RUST_LOG", "actix_web=debug");
|
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
let sys = actix::System::new("r2d2-example");
|
let sys = actix_rt::System::new("r2d2-example");
|
||||||
|
|
||||||
// r2d2 pool
|
// r2d2 pool
|
||||||
let manager = SqliteConnectionManager::file("test.db");
|
let manager = SqliteConnectionManager::file("test.db");
|
||||||
let pool = r2d2::Pool::new(manager).unwrap();
|
let pool = r2d2::Pool::new(manager).unwrap();
|
||||||
|
|
||||||
// Start db executor actors
|
// start http server
|
||||||
let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone()));
|
HttpServer::new(move || {
|
||||||
|
App::new()
|
||||||
// Start http server
|
.state(pool.clone()) // <- store db pool in app state
|
||||||
server::new(move || {
|
.resource("/{name}", |r| r.route(web::get().to_async(index)))
|
||||||
App::with_state(State{db: addr.clone()})
|
})
|
||||||
// enable logger
|
.bind("127.0.0.1:8080")?
|
||||||
.middleware(middleware::Logger::default())
|
.start();
|
||||||
.resource("/{name}", |r| r.method(http::Method::GET).a(index))
|
|
||||||
}).bind("127.0.0.1:8080")
|
|
||||||
.unwrap()
|
|
||||||
.start();
|
|
||||||
|
|
||||||
let _ = sys.run();
|
let _ = sys.run();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user