gpt4 book ai didi

java - mongodb连接线程安全

转载 作者:行者123 更新时间:2023-11-29 04:24:08 27 4
gpt4 key购买 nike

我正在根据一些教程使用以下代码连接到 mongo 数据库。

我对设计有一些疑问:

  1. 可以同时从多个线程调用 MongoConnection.getDB() 函数吗?
  2. 如果不是,我应该同步吗?
  3. 如果设计有问题,它会产生什么样的不良影响?

我是 mongodb 的新手,所以我的问题听起来有点幼稚。

public class MongoConnection {

private static MongoClient mongoClient = null;

private static String IP = "mongodb://user:pwd@localhost:27017/?authSource=demodb&authMechanism=SCRAM-SHA-1";
private static String DATABASE = "demodb";

static {
mongoClient = new MongoClient(new MongoClientURI(IP));
}

private MongoConnection() {

}

public static DB getDB() {
return mongoClient.getDB(DATABASE);
}
}

最佳答案

来自docs :

The MongoClient instance represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

并且来自 previous versions' quick start guides :

The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application.`

所以,MongoClient.getDb(..) 在线程之间应该没有任何问题

关于java - mongodb连接线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47324412/

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