我们需要使用到lazy_static和async_once,这样只初始化一次连接
在Cargo.toml添加:
[dependencies]
lazy_static = "1.4.0"
actix-web = "4"
mongodb = "2.1"
async_once = "0.2.6"
添加 /src/db.rs:
use lazy_static::lazy_static;
use async_once::AsyncOnce;
use mongodb::Client;
lazy_static! {
static ref MONGO_CLIENT: AsyncOnce<Client> = mongo_connect_sync();
}
fn mongo_connect_sync() -> AsyncOnce<Client> {
AsyncOnce::new(async {
Client::with_uri_str("mongodb://user:passwd@localhost:27017").await.unwrap()
})
}
pub struct MongoClient;
pub trait IMongoClient {
async fn init(&self) -> &'static Client;
}
impl IMongoClient for MongoClient {
async fn init(&self) -> &'static Client {
lazy_static::initialize(&MONGO_CLIENT);
&*MONGO_CLIENT.get().await
}
}
/src/main.rs:
mod db;
use crate::db::{MongoClient, IMongoClient};
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/demo")]
async fn demo() -> actix_web::Result<impl Responder> {
let connection : MongoClient = MongoClient {};
let mongo_client = connection.init().await;
...
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(demo)
})
.bind(("0.0.0.0", 8501))?
.run()
.await
}