1
0
mirror of https://github.com/actix/examples synced 2025-01-23 14:24:35 +01:00
examples/diesel/src/main.rs

85 lines
2.2 KiB
Rust
Raw Normal View History

//! Actix web diesel example
//!
//! Diesel does not support tokio, so we have to run it in separate threads.
2018-05-08 11:08:43 -07:00
//! Actix supports sync actors by default, so we going to create sync actor
//! that use diesel. Technically sync actors are worker style actors, multiple
//! of them can run in parallel and process messages from same queue.
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate diesel;
extern crate actix;
extern crate actix_web;
extern crate env_logger;
2018-05-08 11:08:43 -07:00
extern crate futures;
extern crate r2d2;
extern crate uuid;
use actix::prelude::*;
2018-05-20 21:03:29 -07:00
use actix_web::{
http, middleware, server, App, AsyncResponder, FutureResponse, HttpResponse, Path,
State,
};
use diesel::prelude::*;
2018-06-01 11:31:53 -07:00
use diesel::r2d2::ConnectionManager;
use futures::Future;
mod db;
mod models;
mod schema;
use db::{CreateUser, DbExecutor};
/// State with DbExecutor address
struct AppState {
2018-07-16 12:36:53 +06:00
db: Addr<DbExecutor>,
}
/// Async request handler
2018-06-01 11:31:53 -07:00
fn index(
(name, state): (Path<String>, State<AppState>),
) -> FutureResponse<HttpResponse> {
// send async `CreateUser` message to a `DbExecutor`
2018-05-08 11:08:43 -07:00
state
.db
.send(CreateUser {
name: name.into_inner(),
})
.from_err()
2018-05-08 11:08:43 -07:00
.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=info");
env_logger::init();
let sys = actix::System::new("diesel-example");
// Start 3 db executor actors
let manager = ConnectionManager::<SqliteConnection>::new("test.db");
2018-05-08 11:08:43 -07:00
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
2018-05-08 11:08:43 -07:00
let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone()));
// Start http server
server::new(move || {
App::with_state(AppState{db: addr.clone()})
// enable logger
.middleware(middleware::Logger::default())
2018-06-01 11:31:53 -07:00
.resource("/{name}", |r| r.method(http::Method::GET).with(index))
2018-05-08 11:08:43 -07:00
}).bind("127.0.0.1:8080")
.unwrap()
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}