我在一个项目中,需要管理到MongoDB实例和PostgreSQL实例的连接。
我当前的想法是创建一个自定义类型,它将在一个结构中包含一个Arc<Mutex<pgConnection>>和一个Arc<Mutex<MongoConnection>>,这个结构本身就在一个Arc中,它将被传递给Actix app_data初始化函数。
例如:
// this is pseudo-code, kinda
type DbPoolPG = r2d2::Pool<ConnectionManager<PostgreSQL>>;
// wont be an r2d2 pool, MongoDB official drivers handle pooling automatically
type DbPoolMongo = r2d2::Pool<ConnectionManager<MongoDB>>;
struct DatabseConnections {
pg: Arc<Mutex<DbPoolPG>>;
mongo: Arc<Mutex<DbPoolMongo>>;
}
#[actix_web::main]
async fn main() -> io::Result<()> {
// Create connection pools
let PostGresPool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
let MongoPool = mongo.create_connection()
let connections = DatabaseConnections {
pg: Arc::new(Mutex::new(PostGresPool))
mongo: Arc::new(Mutex::new(MongoPool))
}
// Start HTTP server
HttpServer::new(move || {
App::new().app_data(web::Data::new(Arc::new(connections)))
.resource("/{name}", web::get().to(index))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}这个想法似乎有点太简单,但实际工作,其他人有什么想法吗?
发布于 2022-04-29 01:57:50
nvm,只要类型不同,只需调用app_data两次即可。然后通过调用类型来访问它们
https://stackoverflow.com/questions/72051533
复制相似问题