Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

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

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".

My set up is as follows:

The Connection is established in the main thread:

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);

It's used in hundreds of threads:

org.bson.Document oldDoc = DBInteractions.readOneFromDb("articles");

using functions like this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...