gpt4 book ai didi

java - Mongo Java 连接到无效的主机/端口,它真的连接了吗?

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:40 26 4
gpt4 key购买 nike

我有以下代码

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)显然是错误的,但是当我运行这个程序时,它运行并且没有给出任何异常

  • 真的连接了吗?我肯定不会,那么遇到这种情况该如何处理呢?

最佳答案

mongo.getDB("contract") 只是创建一个数据库对象并将其放入 mongo-java-driver 内部缓存中。

据我所知,只有当请求(即查找、插入等操作)发送到数据库时,才会从池中获取连接。

尝试执行 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)

关于java - Mongo Java 连接到无效的主机/端口,它真的连接了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10923251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com