0

我正在使用带有 java-ee 的 mongoDb 数据库

我有我的连接对象:

public class MongoDb {

static Mongo m;
DB db;
DBCollection coll;

public MongoDb(String collection){
    m = null;
    try {
        if(m==null){
            m = new Mongo( "127.0.0.1" );
        }
        db = m.getDB( "game" );
        coll = db.getCollection(collection);
    } catch (UnknownHostException e) {
        System.out.println("Database connexion error");
        e.printStackTrace();
    }
}

public void save(BasicDBObject bdbo){
    coll.insert(bdbo);
}

public void update(BasicDBObject search, BasicDBObject update){
    coll.update(search, update);
}

public void remove(BasicDBObject bdbo){
    coll.remove(bdbo);
}

public long count(){
    long nb = coll.getCount();
    return nb;
}

public List<DBObject> getAll(){
    List<DBObject> list = new ArrayList<DBObject>();
    DBCursor cursor = coll.find().limit(100);
    try {
       while(cursor.hasNext()) {
           list.add(cursor.next());
       }
    } finally {
       cursor.close();
    }
    return list;
}

public List<DBObject> getAll(String key, String value){
    List<DBObject> list = new ArrayList<DBObject>();
    BasicDBObject q = new BasicDBObject();
    q.append(key, Pattern.compile(value, Pattern.CASE_INSENSITIVE));
    DBCursor cursor = coll.find(q).limit(100);
    try {
       while(cursor.hasNext()) {
           list.add(cursor.next());
       }
    } finally {
       cursor.close();
    }
    return list;
}

public DBObject findOne(BasicDBObject bdbo){
    DBObject obj = coll.findOne(bdbo);
    return obj;
}
}

但是每次我发出一个请求时,都会创建一个新的连接,并且 mongodb 上有一个最大连接数,所以如果我达到最大请求数,我必须重新启动 mongodb

有没有办法只初始化一次数据库连接,或者测试连接是否退出?

谢谢

4

1 回答 1

2

是的,只是不要在创建查询对象时重置连接,这样做:

public class MongoDb {

static Mongo m = new Mongo("127.0.0.1");
DB db;
DBCollection coll;

public MongoDb(String collection){
    db = m.getDB( "game" );
    //...

或者重新设计您的类以将数据库代理(存储连接,可能作为单例)与查询对象分开。

于 2013-05-11T15:37:11.833 回答