如何使用Java远程连接到服务器中的MongoDB?

问题描述:

我想通过笔记本电脑上的Java应用程序在服务器上使用MongoDB. 这是我的ufw设置

I want to use my MongoDB on my server from a java application on my laptop. this is my ufw setting

aran@Aran:~$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
22                         ALLOW       Anywhere
80                         ALLOW       Anywhere
443                        ALLOW       Anywhere
21/tcp                     ALLOW       Anywhere
27017                      ALLOW       1.234.56.78
27017                      ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
22 (v6)                    ALLOW       Anywhere (v6)
80 (v6)                    ALLOW       Anywhere (v6)
443 (v6)                   ALLOW       Anywhere (v6)
21/tcp (v6)                ALLOW       Anywhere (v6)
27017 (v6)                 ALLOW       Anywhere (v6)

起初我只有这个规则:

27017                      ALLOW       1.234.56.78

我的IP地址为1.234.56.78,但该地址不起作用,因此我添加了以下规则:

Where 1.234.56.78 is my Ip address but it didn't work so I added this rule:

27017                      ALLOW       Anywhere

但是那也没有帮助.

这是我的Java代码:

Here is my java code:

java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.OFF);
MongoClientURI connectionString = new MongoClientURI("mongodb://123.45.67.89:27017");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase CaptionBotUsers = mongoClient.getDatabase("CaptionBotUsers");
//CaptionBotUsers.createCollection("users", new CreateCollectionOptions().autoIndex(true));
MongoCollection<Document> users = CaptionBotUsers.getCollection("users");
long found = users.count(Document.parse("{_id : " + Long.toString(user.getId()) + "}"));

但是我得到了

com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=123.45.67.89:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]

对于代码的最后一行(找到了 long ... )

For the Last line of the code(long found...)

那我该如何解决呢?

来自MongoDB 文档,它指出,在某些安装中,默认情况下仅监听本地连接(127.0.0.1).

From MongoDB documentation, it states that in some installations by default in only listens local connections (127.0.0.1).

要远程连接,您需要在/etc/mongod.conf 中配置公共可访问接口:

To connect remotely you need to configure a public accesible interface in /etc/mongod.conf:

...
net:
  port: 27017
  bindIp: <your-ip>, 127.0.0.1
...