main.rs
mod framework;
use actix_web::rt::Runtime;
use mongodb::Client;
fn main() {
framework::log::init_logger();
framework::config::init_config("app.conf");
framework::mongo::init_mongo_client();
log::info!("1111");
Runtime::new().unwrap().block_on(aa());
log::info!("1112");
Runtime::new().unwrap().block_on(bb());
log::info!("11113");
log::info!("over");
}
async fn aa() {
log::info!("aa1");
let client = framework::mongo::get_mongo_client();
let rs = client.list_database_names(None, None).await;
log::info!("aa2, {:?}", rs);
}
async fn bb() {
log::info!("bb1");
let client = Client::with_uri_str("mongodb://localhost:27017").await;
log::info!("bb2");
match client {
Ok(v) => {
let rs = v.list_database_names(None, None).await;
log::info!("4441 {:?}", rs);
}
Err(e) => {
log::info!("4442 {:?}", e);
}
}
log::info!("9999");
}
mongo.rs
use crate::framework::config;
use actix_web::rt::Runtime;
use mongodb::Client;
use once_cell::sync::OnceCell;
static INSTANCE: OnceCell<Client> = OnceCell::new();
pub fn init_mongo_client() -> &'static Client {
INSTANCE.get_or_init(|| {
let config = config::get_config();
let mmongodb_uri = config.get("mondo_uri").unwrap();
let client = Runtime::new()
.unwrap()
.block_on(Client::with_uri_str(&mmongodb_uri));
log::info!("build mongodb client, uri={}", mmongodb_uri);
// log::info!(" ### {:#?}", client);
client.ok().unwrap()
})
}
pub fn get_mongo_client() -> &'static Client {
INSTANCE.get().unwrap()
}
输出
2021-05-17 16:32:46 INFO [demo3::framework::log] env_logger initialized.
2021-05-17 16:32:46 INFO [demo3::framework::mongo] build mongodb client, uri=mongodb://localhost:27017
2021-05-17 16:32:46 INFO [demo3] 1111
2021-05-17 16:32:46 INFO [demo3] aa1
2021-05-17 16:33:16 INFO [demo3] aa2, Err(Error { kind: ServerSelectionError { message: "Server selection timeout: No available servers. Topology: { Type: Unknown, Servers: [ { Address: localhost:27017, Type: Unknown }, ] }" }, labels: [] })
2021-05-17 16:33:16 INFO [demo3] 1112
2021-05-17 16:33:16 INFO [demo3] bb1
2021-05-17 16:33:16 INFO [demo3] bb2
2021-05-17 16:33:16 INFO [demo3] 4441 Ok(["admin", "config", "local", "table"])
2021-05-17 16:33:16 INFO [demo3] 999
2021-05-17 16:33:16 INFO [demo3] 11113
2021-05-17 16:33:16 INFO [demo3] over
问题:为啥用aa的方式连接mongodb成功,但是一执行操作就报超时,bb的方式就没问题?
1
共 5 条评论, 1 页
评论区
写评论感谢大佬。
--
👇
modraedlau: 使用一个Runtime,初始化的时候把Runtime作为参数传递过去:
使用一个Runtime,初始化的时候把Runtime作为参数传递过去:
那像这种全局共用的数据源应该怎么初始化才是正解?
--
👇
modraedlau: 你的
Client::with_uri_str
和client.list_database_names
明显处于两个不同的async Runtime。你的
Client::with_uri_str
和client.list_database_names
明显处于两个不同的async Runtime。求解惑