我以为这个问题被问了好几次,但我不得不再问一遍。因为为这个问题提供的解决方案并没有给我一个确切的答案来摆脱这个该死的错误。
当我尝试将文档插入数据库时,我使用 mongo-java-driver-2.12.4
和 mongo.jar
出现以下错误。任何帮助表示赞赏。
错误:
Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=127.0.0.1:27000, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27001, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27002, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
代码:
public class MongoDbConnectDatabase {
public static void main(String[] args) {
// To connect to mongodb server
try {
List<ServerAddress> lstServer = new ArrayList<ServerAddress>();
lstServer.add(new ServerAddress("127.0.0.1", 27000));
lstServer.add(new ServerAddress("127.0.0.1", 27002));
lstServer.add(new ServerAddress("127.0.0.1", 27001));
MongoClient mongoClient = new MongoClient(lstServer);
// Now connect to your database
DB db = mongoClient.getDB("test");
System.out.println("connect to database successfully");
DBCollection coll = db.createCollection("mycol", null);
System.out.println("Collection created successfully");
DBCollection colReceived= db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("url", "http://www.tutorialspoint.com/mongodb/").
append("by", "tutorials point");
colReceived.insert(doc);
System.out.println("Document inserted successfully");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最佳答案
您收到拒绝连接。你确定 mongod 正在运行吗?
尝试连接mongoclient:
mongo 127.0.0.1:27000/test
这适用于所有三个实例(27000、27002、27001)。
如果您对 mongoclient 也有问题,请检查您的日志。
关于java - com.mongodb.MongoTimeoutException : Timed out after 10000 ms while waiting to connect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38432880/