gpt4 book ai didi

java - 如何在Java中正确使用MongoDB多线程?

转载 作者:行者123 更新时间:2023-11-30 02:39:38 24 4
gpt4 key购买 nike

我正在使用 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/

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