Cli*_*ger 6 rust rust-diesel actix-web
我为 MySQL 数据库创建了一个池,如下所示:
let database_url = env::var("DATABASE_URL").expect("set DATABASE_URL");
let manager = ConnectionManager::<MysqlConnection>::new(database_url);
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
Run Code Online (Sandbox Code Playgroud)
像这样包含在 actix 中:
HttpServer::new(move || App::new()
.data(pool.clone()) // <-- HERE
.service(
web::resource("/infos")
.route(web::post().to(get_infos))
))
.bind("127.0.0.1:8080")?
.start();
println!("Starting http server: 127.0.0.1:8080");
Run Code Online (Sandbox Code Playgroud)
问题来了,如何在这个 info 函数中使用它:
pub fn get_infos(conn: &MysqlConnection) -> Vec<Book> {
all_books
.order(books::id.desc())
.load::<Book>(conn)
.expect("error loading the books")
}
Run Code Online (Sandbox Code Playgroud)
直接将 MySQL 连接的一个实例传递给 get_infos 运行良好,但使用池我不知道如何处理它?!有什么帮助吗?
为了获得更多说明,我的目标是使用 POOLING 而不是仅使用一个实例,就像此代码中的情况一样:
let database_url = env::var("DATABASE_URL").expect("set DATABASE_URL");
let conn = MysqlConnection::establish(&database_url).unwrap();
// And then passing as argument "conn" to get_infos function.
Run Code Online (Sandbox Code Playgroud)
我在之前的代码中向actix发起了POOL:
.data(pool.clone()) // <-- HERE
但如何将它作为参数传递给get_infos函数。
再次预先感谢您的帮助。
对于您的处理程序;只需添加池作为参数,然后您可以将固定连接传递给下游函数:
// Data = actix_web::web::Data
pub fn get_all_books(pool: Data<Pool>) -> HttpResponse {
let connection = pool.get().expect("Failed to get connection");
let books = get_infos(&connection);
HttpResponse::Ok().json(books)
}
pub fn get_infos(connection: &MysqlConnection) -> Vec<Book> {
all_books
.order(books::id.desc())
.load::<Book>(conn)
.expect("error loading the books")
}
Run Code Online (Sandbox Code Playgroud)