[英]Java Mongodb connection failed
我有一个java应用程序,它使用大约3000个可重用的线程,它始终运行并处理队列中的项目。 我使用MongoDB进行数据存储,每次运行它都能完美地运行大约40分钟,之后Mongo DB Object开始返回查询的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;
}
}
你应该切换到Morphia! https://github.com/mongodb/morphia
使用工厂模式生成单个Mongo实例并将其绑定到Morphia Datastore对象。 然后,您可以使用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,也可以使用CDI注入数据存储区
@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
Datastore ds;
奖金
为了进一步将代码与MongoDB分离,创建数据访问对象(DAO)以访问包含Morphia数据存储对象的数据库将是正确的设计。 您的DAO将具有您希望在数据库上使用的方法(获取,创建,保存,删除)。 这样,如果您决定离开MongoDB,您只需要更改DAO对象而不是所有代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.