如何防止 mongodb 上的 java 驱动程序关闭连接池?

How to keep the connection pool from closing with a java driver on a mongodb?

我正在从 java 驱动程序 2.12.3 升级到 3.3.0。奇怪的是 collection 池似乎突然 "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();
}

对于每次数据库交互,我都会收到这样的警告:

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.

看起来连接池在一次交互之后就关闭了。但为什么? 很疑惑大家有什么想法吗?

https://api.mongodb.com/java/3.1/com/mongodb/MongoClientOptions.html

看看link。有几种方法可能对您有所帮助。 查看 connectionconnection pool.

的超时相关方法

编辑:添加了正确答案(在下面的评论中)

MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build(); 
MongoClient client = new MongoClient("host", options);
MongoClientOptions options = new MongoClientOptions.Builder().socketKeepAlive(true).build();

socketKeepAlive 现在已弃用
它现在 默认 true 并且不建议禁用它。