同时使用 async tokio-postgres 不是 `Send`

Using async tokio-postgres concurrently is not `Send`

我正在尝试使用 tokio-postgres crate 实现异步数据库访问。这是我尝试过的:

use tokio_postgres::{Client, NoTls, Error};

pub struct Database{
    client: Mutex<Client>
}

impl Database {

    pub async fn some_db_operation(&self, /* args */) -> Result<(), Error> {
        let connection = &mut self.client.lock().expect("Mutex was poisoned");
        let transaction = &mut connection.transaction().await?;
        //executing some queries
        Ok(())
    }

} 

问题是我想使用 warp 访问数据库作为传入 http 请求处理的一部分,因此一切都应该是 Send。我收到以下错误:

  --> src/db.rs:27:32
   |
26 |         let connection = &mut self.client.lock().expect("Mutex was poisoned");
   |                               ----------------------------------------------- has type `std::sync::MutexGuard<'_, tokio_postgres::client::Client>` which is not `Send`
27 |         let transaction = &mut connection.transaction().await?;
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ await occurs here, with `self.client.lock().expect("Mutex was poisoned")` maybe used later

是否有解决方法Send

同步客户端没有这样的问题。

MutexGuard(在 Mutex 上调用 lock() 的结果)不是 SendThe relevant part in the docs!Send 的手动实现(“不是 Send”)。

我强烈建议研究某种连接池,也许 deadpool_postgres 是围绕 tokio-postgres 构建的。在互斥锁后面使用单个客户端可能会降低你的异步性能。