gpt4 book ai didi

java - mongodb打开连接问题

转载 作者:IT老高 更新时间:2023-10-28 13:26:41 28 4
gpt4 key购买 nike

我的 mongo 控制台中有以下日志:

Tue Jul 23 17:20:01.301 [initandlisten] waiting for connections on port 27017
Tue Jul 23 17:20:01.401 [websvr] admin web console waiting for connections on port 28017
Tue Jul 23 17:20:01.569 [initandlisten] connection accepted from 127.0.0.1:58090 #1 (1 connection now open)
Tue Jul 23 17:20:01.570 [initandlisten] connection accepted from 127.0.0.1:58089 #2 (2 connections now open)
Tue Jul 23 17:20:21.799 [initandlisten] connection accepted from 127.0.0.1:58113 #3 (3 connections now open)
....
....
....

同样,日志继续,现在它在 112 中。每次我启动 mongo 服务器时都会发生这种情况。我的代码中只有一个单例连接。这里可能是什么问题:

public static DB getConnection(String databaseName) throws AppConnectionException {

if (null != db) {
Logger.debug("Returning existing db connection...!");
return db;
}

Logger.debug("Creating new db connection...!");
final String connStr = PropertyRetreiver.getPropertyFromConfigurationFile("rawdata.url");

try {

final MongoClientURI uri = new MongoClientURI(connStr);
final MongoClient client = new MongoClient(uri);
db = client.getDB(databaseName);

} catch (UnknownHostException e) {
throw new AppConnectionException(
"Unable to connect to the given host / port.");
}

return db;
}

最佳答案

MongoClient 有内部连接池。可以配置最大连接数(默认为 100)。您可以像这样使用 MongoClientOptions 进行设置:

MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(100)
.autoConnectRetry(true)
.build();

然后将这些选项提供给 MongoClient(在 Mongo Java API v2.11.1 中检查)。池中的连接保持打开状态(打开和关闭连接通常是一项昂贵的操作),以便以后可以重用。

我还将使用 enum 重构您的 MongoDB 客户端单例,例如避免将 synchronized 放在此方法上。

这是我的意思的草图:

public enum MongoDB {
INSTANCE;

private static final String MONGO_DB_HOST = "some.mongohost.com";
private Mongo mongo;
private DB someDB;

MongoDB() {

MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(100)
.autoConnectRetry(true)
.readPreference(ReadPreference.secondaryPreferred())
.build();

try {
mongo = new MongoClient(MONGO_DB_HOST, options);
} catch (UnknownHostException e) {
e.printStackTrace();
}

someDB = mongo.getDB("someDB");
//authenticate if needed
//boolean auth = someDB.authenticate("username", "password".toCharArray());
//if(!auth){
// System.out.println("Error Connecting To DB");
//}
}

public DB getSomeDB() {
return someDB;
}

//call it on your shutdown hook for example
public void close(){
mongo.close();
}
}

然后,您可以通过

访问您的数据库
MongoDB.INSTANCE.getSomeDB().getCollection("someCollection").count();

关于java - mongodb打开连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17810527/

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