在https://actix.rs/docs/databases/有一个例子:
async fn index(pool: web::Data<DbPool>, name: web::Path<(String)>) -> impl Responder {
let name = name.into_inner();
let conn = pool.get().expect("couldn't get db connection from pool");
let user = web::block(move || actions::insert_new_user(&conn, &user))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
Ok(HttpResponse::Ok().json(user))
}
如果我在一个函数中需要多个 SQL 查询怎么办?由于移动,以下显然不起作用conn
:
async fn index(pool: web::Data<DbPool>, name: web::Path<(String)>) -> impl Responder {
let name = name.into_inner();
let conn = pool.get().expect("couldn't get db connection from pool");
let user1 = web::block(move || actions::insert_new_user(&conn, &user))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
// ... asynchronous code here
let user2 = web::block(move || actions::insert_new_user(&conn, &user))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
Ok(HttpResponse::Ok().json(user))
}
我可以通过重复调用来接收多个连接pool.get()
,但是当一个连接足够时打开新的 SQL 连接效率低下。
那么,如何处理呢?