我正在使用 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(只是为了确定,我只有一个 DB 连接实例)。
@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”对象实例,我也无法在不创建新连接的情况下获取数据,为什么我不能共享这个连接,因为它应该是由于池化?}