【问题标题】:Imlementing connection pooling in a rust/diesel app with r2d2使用 r2d2 在 rust/diesel 应用程序中实现连接池
【发布时间】:2021-10-08 12:16:56
【问题描述】:

我正在尝试在 rust/diesel/rocket 应用程序中实现连接池。不知道如何保证establish_pooled_connection()方法的内容只被调用一次,从而准备连接池。

这是我的代码。

来自 lib.rs

pub fn establish_pooled_connection() -> PooledConnection<ConnectionManager<PgConnection>> {
    dotenv().ok();

    let database_url = env::var("DB_URL")
        .expect("DATABASE_URL must be set");

    let manager = ConnectionManager::<PgConnection>::new(&database_url);
    let pool = r2d2::Pool::builder().build(manager).expect("Failed to create pool.");
    let conn = pool.clone().get().unwrap();
    return conn;
}

这里我在ma​​in.rs中使用了上面的方法:

#[get("/", format = "json")]
fn find_all() -> Json<Vec<Person>> {
    let connection = establish_pooled_connection();

    let all: QueryResult<Vec<Person>> = person::table().get_results(&connection);
    ...

这里的问题是每个get 方法(例如上面)调用establish_pooled_connection() 并且一切都被重新实例化......

我来自 java 世界,依赖注入允许我们避免重新实例化。

在 rust/diesel 应用程序中实现连接池的正确方法是什么?

【问题讨论】:

    标签: rust rust-diesel r2d2


    【解决方案1】:

    您不会在每个处理程序中创建新连接,而是使用框架的一些状态共享机制。

    请参阅here 了解如何在火箭中使用状态的指南,这将是一个很好的起点。

    【讨论】:

      猜你喜欢
      • 2017-09-02
      • 2021-10-31
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      相关资源
      最近更新 更多