我有以下代码
public class MongoService {
private final Mongo mongo;
private static final Logger LOGGER = LoggerFactory.getLogger(MongoService.class);
public MongoService() throws UnknownHostException {
mongo = new Mongo("localhot", 2707);
DB db = mongo.getDB("contract");
LOGGER.info(db.getCollection("Test").getName());
}
public Mongo getMongoInstance() {
return mongo;
}
public void insert() {
LOGGER.info("will run mongo insert now");
}
public void query() {
LOGGER.info("will run query now");
}
public static void main(String args[]) throws UnknownHostException {
MongoService mongoService = new MongoService();
mongoService.insert();
mongoService.query();
}
}
输出
15:26:07.509 [main] INFO c.s.s.business.persist.MongoService - Test
15:26:07.514 [main] INFO c.s.s.business.persist.MongoService - will run mongo insert now
15:26:07.514 [main] INFO c.s.s.business.persist.MongoService - will run query now
主机(应该是localhost)和端口(应该是27017)显然是错误的,但是当我运行这个程序时,它运行并没有给出任何例外
真的是连接吗?我肯定不会,那么如何处理这种情况?
答案 0 :(得分:1)
mongo.getDB(“contract”)只是创建一个DB对象并将其放入mongo-java-driver内部缓存中。
AFAIK,只有在向数据库发送请求(即查找,插入,...等操作)时才从池中获取连接。
尝试执行findOne操作并发生IOException:
java.io.IOException: couldn't connect to [/127.0.0.1:2017] bc:java.net.ConnectException: Connection refused
at com.mongodb.DBPort._open(DBPort.java:228)
at com.mongodb.DBPort.go(DBPort.java:112)
at com.mongodb.DBPort.go(DBPort.java:93)
at com.mongodb.DBPort.findOne(DBPort.java:146)
at com.mongodb.DBPort.runCommand(DBPort.java:157)
at com.mongodb.DBTCPConnector.fetchMaxBsonObjectSize(DBTCPConnector.java:457)
at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:444)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:209)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:305)
at com.mongodb.DBCollection.findOne(DBCollection.java:647)
at com.mongodb.DBCollection.findOne(DBCollection.java:626)
at com.mongodb.DBCollection.findOne(DBCollection.java:615)