1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-26 10:27:42 +02:00

add r2d2 example

This commit is contained in:
Nikolay Kim
2018-02-15 23:05:10 -08:00
parent 8607c51bcf
commit 3c95823e53
6 changed files with 126 additions and 0 deletions

41
examples/r2d2/src/db.rs Normal file
View File

@ -0,0 +1,41 @@
//! Db executor actor
use std::io;
use uuid;
use actix_web::*;
use actix::prelude::*;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
/// 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"))?)
}
}

63
examples/r2d2/src/main.rs Normal file
View File

@ -0,0 +1,63 @@
//! Actix web r2d2 example
extern crate serde;
extern crate serde_json;
extern crate uuid;
extern crate futures;
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate r2d2;
extern crate r2d2_sqlite;
extern crate rusqlite;
use actix::*;
use actix_web::*;
use futures::future::Future;
use r2d2_sqlite::SqliteConnectionManager;
mod db;
use db::{CreateUser, DbExecutor};
/// State with DbExecutor address
struct State {
db: Addr<Syn, DbExecutor>,
}
/// Async request handler
fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>> {
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(httpcodes::HTTPOk.build().json(user)?),
Err(_) => Ok(httpcodes::HTTPInternalServerError.into())
}
})
.responder()
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=debug");
let _ = env_logger::init();
let sys = actix::System::new("r2d2-example");
let manager = SqliteConnectionManager::file("test.db");
let pool = r2d2::Pool::new(manager).unwrap();
// Start db executor actors
let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone()));
// Start http server
let _addr = HttpServer::new(move || {
Application::with_state(State{db: addr.clone()})
// enable logger
.middleware(middleware::Logger::default())
.resource("/{name}", |r| r.method(Method::GET).a(index))})
.bind("127.0.0.1:8080").unwrap()
.start();
let _ = sys.run();
}