How to use DB connections in Actix several times per function?
You just need to move the reference, not the connection itself:
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 conn = &conn_;
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))
}
Your problem can be reduced to (not working version):
struct Conn {}
fn foo(_: &Conn) {}
fn main() {
let conn_ = Conn {};
(move || foo(&conn_))();
(move || foo(&conn_))();
}
Playground
Working version:
struct Conn {}
fn foo(_: &Conn) {}
fn main() {
let conn_ = Conn {};
let conn = &conn_;
(move || foo(conn))();
(move || foo(conn))();
}
Playground