作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 mongo-java-driver-3.0.0 库在我的 MongoDB 实例中插入许多数据。问题是,当我尝试使用多个线程(模拟多个用户)时,在进行一些插入后会发生以下错误:
INFORMAÇÕES: Closed connection [connectionId{localValue:816}] to
localhost:27017 because the pool has been closed. Exception in thread
"user_4" com.mongodb.MongoSocketReadException:
Prematurely reached end of stream
我调用实例并进行插入的代码是:
public static FachadaMongo getInstancia() {
if (instancia == null) {
instancia = new FachadaMongo();
}
return instancia;
}
public MongoDatabase getDB(String HOST, String PORT, String DB_NAME) {
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
//build the connection options
builder.maxConnectionIdleTime(60000);//set the max wait time in (ms) 60 segundos
MongoClientOptions opts = builder.build();
int port = Integer.parseInt(PORT);
MongoClient mongoClient = new MongoClient(new ServerAddress(HOST, port), opts);
MongoDatabase db = mongoClient.getDatabase(DB_NAME);
return db;
}
public MongoCollection getColecao(String HOST, String PORT, String DB_NAME, String colecao) {
MongoCollection col = FachadaMongo.getInstancia().getDB(HOST, PORT, DB_NAME).getCollection(colecao);
return col;
}
public void insert(String HOST, String PORT, String DB_NAME, Document documento) {
this.getColecao(HOST, PORT, DB_NAME, "documentos").insertOne(documento);
}
即使我仅在一个线程中使用此代码,一段时间后也会出现相同的错误。使用多个线程,错误来得更快。如果有人可以帮助我,我将不胜感激,我大学的最终工作取决于此。
最佳答案
经过多次测试,我可以找到问题的原因。在 getDB 方法中,我为数据库中的每个插入创建一个新连接。将连接数乘以客户端数,我的数据库“过度连接”了。我通过替换行来修复它
MongoClient mongoClient = new MongoClient(new ServerAddress(HOST, port), opts);
用行:
MongoClient mongoClient;
在类(class)的开头,以及以下行:
if (mongoClient == null) mongoClient = new MongoClient(new ServerAddress(HOST, port), opts);
在我删除的另一个位置。
现在运行良好。
关于java - 如何在Java中正确使用MongoDB多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42122583/
我是一名优秀的程序员,十分优秀!