如何防止连接池在 mongodb 上使用 java 驱动程序关闭?
我正在从 java 驱动程序 2.12.3 升级到 3.3.0.奇怪的是,收集池似乎突然行动起来".
I'm in the middle of upgrading from java driver 2.12.3 to 3.3.0. Curiously it seems that the collection pool is suddenly "acting up".
我的设置如下:
在主线程中建立连接:
mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
mongoClient.setWriteConcern(new WriteConcern(0, 10)); // deprecated, replace soon
database = mongoClient.getDatabase("Example");
// java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);
在数百个线程中使用:
org.bson.Document oldDoc = DBInteractions.readOneFromDb("articles");
使用这样的函数:
static synchronized Document readOneFromDb(String col) {
return database.getCollection(col).find().limit(1).sort(new Document().append("count", 1)).first();
}
对于每次数据库交互,我都会收到这样的警告:
And for every DB interaction I get such a warning:
Sep 26, 2016 2:33:19 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMATION: Closed connection [connectionId{localValue:42, serverValue:248}] to localhost:27017 because the pool has been closed.
看起来好像连接池在一次交互后就关闭了.但为什么?非常不解 有人有什么想法吗?
It looks as if the connection pool is closed after just one interaction. But why? very puzzled Anyone an idea?
推荐答案
https://api.mongodb.com/java/3.1/com/mongodb/MongoClientOptions.html
查看链接.有几种方法可能对您有所帮助.查看 connection 和 connection pool 的超时相关方法.
Look at the link. There are several method that can probably help you. Look into the timeout related methods for connection and connection pool.
编辑:添加正确答案(在下面的评论中)
EDIT: added the correct answer (it was in the comments below)
MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build();
MongoClient client = new MongoClient("host", options);
相关文章