1

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 连接效率低下。

那么,如何处理呢?

4

1 回答 1

2

您只需要移动参考,而不是连接本身:

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))
}

您的问题可以简化为(非工作版本):


struct Conn {}

fn foo(_: &Conn) {}


fn main() {

    let conn_ = Conn {};
    
    (move || foo(&conn_))();
    (move || foo(&conn_))();
    
}

操场

工作版本:

struct Conn {}

fn foo(_: &Conn) {}


fn main() {

    let conn_ = Conn {};
    let conn = &conn_;
    (move || foo(conn))();
    (move || foo(conn))();
    
}

操场

于 2022-01-23T16:10:04.180 回答