Rust Actix-web中使用mongodb异步连接

我们需要使用到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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值