2

有许多文章解释了使用 SQLite 进行多线程访问的问题,但我找不到任何简单的解决方案。如何从多个线程同时工作的 Web 服务器访问 SQLite?

来源(仍然无法解释任何简单的解决方法):

4

1 回答 1

1

您可以使用r2d2-sqlite连接池 +std::sync::Arc对 SQLite 进行多线程访问。例子:

[dependencies]
r2d2_sqlite = "0.16.0"
r2d2 = "0.8.8"

在锈中:

fn main() {
    let sqlite_file = "my.db";
    let sqlite_connection_manager = SqliteConnectionManager::file(sqlite_file);
    let sqlite_pool = r2d2::Pool::new(sqlite_connection_manager)
        .expect("Failed to create r2d2 SQLite connection pool");
    let pool_arc = Arc::new(sqlite_pool);

    let pool = pool_arc.clone();
    whatever.method(move || {
        let connection = pool.get();
        // ...
    });

    let pool = pool_arc.clone();
    whatever.method(move || {
        let connection = pool.get();
        // ...
    });
}
于 2020-06-24T17:02:45.273 回答