gpt4 book ai didi

mongodb - 替代将 'await'与lazy_static一起使用!使用rust 的宏?

转载 作者:行者123 更新时间:2023-12-03 11:29:56 25 4
gpt4 key购买 nike

我想在项目中使用Async MongoDB。

不想传递客户端,因为它需要传递多个任务和线程。因此,我使用延迟静态保留了一个静态客户端。但是我不能在初始化块中使用await。

我该怎么办才能解决此问题?

也欢迎提出在不使用lazy_static的情况下完全不同地进行操作的建议。

use std::env;
use futures::stream::StreamExt;
use mongodb::{
bson::{doc, Bson},
options::ClientOptions,
Client,
};

lazy_static! {
static ref MONGO: Option<Client> = {
if let Ok(token) = env::var("MONGO_AUTH") {
if let Ok(client_options) = ClientOptions::parse(&token).await
^^^^^
{
if let Ok(client) = Client::with_options(client_options) {
return Some(client);
}
}
}
return None;
};
}

最佳答案

我根据 rust 论坛中某人的建议采用了这种方法。

static MONGO: OnceCell<Client> = OnceCell::new();
static MONGO_INITIALIZED: OnceCell<tokio::sync::Mutex<bool>> = OnceCell::new();

pub async fn get_mongo() -> Option<&'static Client> {
// this is racy, but that's OK: it's just a fast case
let client_option = MONGO.get();
if let Some(_) = client_option {
return client_option;
}
// it hasn't been initialized yet, so let's grab the lock & try to
// initialize it
let initializing_mutex = MONGO_INITIALIZED.get_or_init(|| tokio::sync::Mutex::new(false));

// this will wait if another task is currently initializing the client
let mut initialized = initializing_mutex.lock().await;
// if initialized is true, then someone else initialized it while we waited,
// and we can just skip this part.
if !*initialized {
// no one else has initialized it yet, so

if let Ok(token) = env::var("MONGO_AUTH") {
if let Ok(client_options) = ClientOptions::parse(&token).await {
if let Ok(client) = Client::with_options(client_options) {
if let Ok(_) = MONGO.set(client) {
*initialized = true;
}
}
}
}
}
drop(initialized);
MONGO.get()
}

关于mongodb - 替代将 'await'与lazy_static一起使用!使用rust 的宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62351945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com