gpt4 book ai didi

Java Mongodb 连接失败

转载 作者:可可西里 更新时间:2023-11-01 09:15:10 24 4
gpt4 key购买 nike

我有一个 Java 应用程序,它使用大约 3000 个可重复使用的线程,这些线程始终在运行并处理队列中的项目。我使用 MongoDB 作为我的数据存储,每次我运行它时它都能完美运行大约 40 分钟,之后 Mongo DB 对象开始返回查询的 Nullpointer 异常。起初我怀疑这可能是由于连接丢失,但正如您在 Google 监控图中看到的那样,连接仍然打开,但 Mongo 查询的数量明显减少。我在这里遗漏了什么吗?

我的 MongoDB 类是这样的:

public class MongoDB {

private static MongoClient mongoClient;

private static MongoClient initMongoClient() {
ServerAddress server = new ServerAddress("X.X.X.X");

MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.threadsAllowedToBlockForConnectionMultiplier(50000);
builder.socketKeepAlive(true);
builder.connectionsPerHost(10000);
builder.minConnectionsPerHost(2500);


MongoClientOptions options = builder.build();
MongoClient mc = new MongoClient(server, options);
mongoClient = mc;
return mc;
}

public static MongoClient getMongoClient() {
if(mongoClient == null) {
mongoClient = initMongoClient();
}

return mongoClient;
}

public static DB getDb() {
DB db;
MongoClient mc;
try {
mc = getMongoClient();
mc.getDatabaseNames();
} catch(MongoException e) {
mc = initMongoClient();
}
db = mc.getDB("tina");
return db;
}

}

enter image description here

最佳答案

你应该改用 Morphia! https://github.com/mongodb/morphia

使用工厂模式生成单个 Mongo 实例并将其绑定(bind)到 Morphia 数据存储对象。然后,您可以使用 Datastore 对象与您的 MongoDB 进行交互。

public class DatastoreFactory {
private static Datastore ds;

public static Datastore getDatastore() {
//Lazy load the datastore
if(ds == null) {
try {
Morphia morphia = new Morphia();
ds = morphia.createDatastore(
new MongoClient("server", port, "database"));
//... Other datastore options
} catch(Exception e) {
// Handle it
}
}
return ds;
}

然后在任何需要 MongoDB 实例的地方,您只需使用 Datastore 对象并从工厂获取它

Datastore ds = DatastoreFactory.getDatastore();

如果您喜欢的话,您也可以使用 CDI 注入(inject)数据存储

@Singleton
public class DatastoreFactory {
private Datastore ds;

@Produces
public Datastore getDatastore() {
//Lazy load the datastore
if(ds == null) {
try {
Morphia morphia = new Morphia();
ds = morphia.createDatastore(
new MongoClient("server", port, "database"));
//... Other datastore options
} catch(Exception e) {
// Handle it
}
}
return ds;
}

然后像这样注入(inject)

@Inject
Datastore ds;

奖金

为了进一步将您的代码与 MongoDB 分离,创建数据访问对象 (DAO) 以访问包含 Morphia 数据存储对象的数据库是正确的设计。您的 DAO 将具有您希望在数据库上使用的方法(获取、创建、保存、删除)。这样,如果您决定放弃 MongoDB,您只需更改 DAO 对象而不是所有代码!

关于Java Mongodb 连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31611884/

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