MongoDb在集合上的每个操作都创建连接

时间:2013-04-17 13:27:49

标签: mongodb ejb mongodb-java nosql

我正在使用mongodb-java-driver,除此之外别无其他。我创建了与Mongo连接的单一EJB。

@Singleton
public class MongoConnection {

private DB db = null;
private MongoClient mongoClient = null;

@PostConstruct
public void init() {
  try {
    mongoClient = new MongoClient("localhost", 27017);
    db = mongoClient.getDB("mydb");
  } catch (UnknownHostException e) {
    e.printStackTrace();
}
}

public MongoConnection() {
}

public DB getDb() {
  return db;
}
public DBCollection getCollectionInDatabase(String collection) {
  DBCollection coll;
  coll = db.getCollection(collection);
  return coll;
}
}

我在ApplicationScoped bean(JSF)中得到这个ejb(只是为了确保,我将只有一个数据库连接实例)。

@Named("appMongo")
@ApplicationScoped
public class MongoApplicationScope implements Serializable{

private static final long serialVersionUID = 1L;
@EJB MongoConnection mu;


public MongoConnection getMu() {
return mu;
}

public void setMu(MongoConnection mu) {
this.mu = mu;
}
}

然后在请求范围的bean中,我从db

获取数据
@Named("mongoBean")
@SessionScoped
public class MongoBean implements Serializable {

private static final long serialVersionUID = 1L;
@Inject MongoApplicationScope mongoAccess;
public void mongoDzialanie() {
DBCollection coll = mongoAccess.getMu().getDb().getCollection("oko"); //at this step everything is correct  
System.out.println(coll.getCount()); //new connection is created text from mongoDB console -> connection accepted from 127.0.0.1:57700 #2 (2 connections now open)

}

为什么即使我有相同的“db”对象实例,我也无法在不创建新连接的情况下获取数据,为什么我不能共享此连接,因为它应该归于池?     }

0 个答案:

没有答案