Neu*_*oXc 1 iron rust rust-diesel
在编写测试时,我希望能够在请求中注入连接,以便我可以将整个测试用例包装在事务中(即使测试用例中有多个请求).
我尝试使用BeforeMiddleware我可以在我的测试用例中链接的插入连接,如下所示:
pub type DatabaseConnection = PooledConnection<ConnectionManager<PgConnection>>;
pub struct DatabaseOverride {
conn: DatabaseConnection,
}
impl BeforeMiddleware for DatabaseOverride {
fn before(&self, req: &mut Request) -> IronResult<()> {
req.extensions_mut().entry::<DatabaseOverride>().or_insert(self.conn);
Ok(())
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我在尝试执行此操作时遇到编译错误:
error: the trait bound `std::rc::Rc<diesel::pg::connection::raw::RawConnection>: std::marker::Sync` is not satisfied [E0277]
impl BeforeMiddleware for DatabaseOverride {
^~~~~~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::rc::Rc<diesel::pg::connection::raw::RawConnection>` cannot be shared between threads safely
note: required because it appears within the type `diesel::pg::PgConnection`
note: required because it appears within the type `r2d2::Conn<diesel::pg::PgConnection>`
note: required because it appears within the type `std::option::Option<r2d2::Conn<diesel::pg::PgConnection>>`
note: required because it appears within the type `r2d2::PooledConnection<r2d2_diesel::ConnectionManager<diesel::pg::PgConnection>>`
note: required because it appears within the type `utility::db::DatabaseOverride`
note: required by `iron::BeforeMiddleware`
error: the trait bound `std::cell::Cell<i32>: std::marker::Sync` is not satisfied [E0277]
impl BeforeMiddleware for DatabaseOverride {
^~~~~~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::cell::Cell<i32>` cannot be shared between threads safely
note: required because it appears within the type `diesel::pg::PgConnection`
note: required because it appears within the type `r2d2::Conn<diesel::pg::PgConnection>`
note: required because it appears within the type `std::option::Option<r2d2::Conn<diesel::pg::PgConnection>>`
note: required because it appears within the type `r2d2::PooledConnection<r2d2_diesel::ConnectionManager<diesel::pg::PgConnection>>`
note: required because it appears within the type `utility::db::DatabaseOverride`
note: required by `iron::BeforeMiddleware`
Run Code Online (Sandbox Code Playgroud)
柴油的连接是否有办法解决这个问题?我在Github上找到了几个使用pg箱子来做这个的例子,但是我想继续使用柴油.
这个答案肯定会解决问题,但并不是最优的.如上所述,您不能共享单个连接,因为它不是线程安全的.但是,虽然将其包装在一个Mutex使其成为线程安全的,但它会强制所有服务器线程使用单个连接.相反,您想要使用连接池.
你可以使用r2d2和r2d2-diesel箱来完成这个任务.这将根据需要建立多个连接,并在可能的情况下以线程安全的方式重用它们.
| 归档时间: |
|
| 查看次数: |
1196 次 |
| 最近记录: |