首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向铁中间件中注入柴油连接

向铁中间件中注入柴油连接
EN

Stack Overflow用户
提问于 2016-06-23 13:53:21
回答 1查看 1.9K关注 0票数 2

在编写测试时,我希望能够向请求中注入一个连接,以便能够将整个测试用例封装在一个事务中(即使测试用例中有多个请求)。

我尝试使用BeforeMiddleware来实现这一点,我可以将其链接到测试用例中来插入连接,如下所示:

代码语言:javascript
复制
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(())
    }
}

但是,我在尝试这样做时遇到了一个编译错误:

代码语言:javascript
复制
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`

有什么办法可以绕过柴油的连接吗?我已经找到了几个使用pg机箱来完成这个任务的例子,但是我还是想继续使用柴油。

EN

回答 1

Stack Overflow用户

发布于 2016-08-17 10:55:28

这个答案当然会解决这个问题,但它不是最优的。如前所述,您不能共享一个连接,因为它不是线程安全的。但是,在将其封装在Mutex中使其线程安全的同时,它将强制所有服务器线程使用单个连接。相反,您希望使用连接池。

您可以使用r2d2R2D2-柴油板条箱来完成这一任务。这将根据需要建立多个连接,并在可能时以线程安全的方式重用它们。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37993668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档