如何用java远程连接到我服务器上的mongodb?

r8uurelv  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(397)

我想从笔记本电脑上的java应用程序使用服务器上的mongodb。这是我的ufw设置

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

其中1.234.56.78是我的ip地址,但它不起作用,因此我添加了以下规则:

27017                      ALLOW       Anywhere

但这也没用。
以下是我的java代码:

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 found…)
我该怎么解决这个问题?

uidvcgyl

uidvcgyl1#

从mongodb文档可以看出,在某些安装中,默认情况下in只侦听本地连接(127.0.0.1)。
要远程连接,您需要在/etc/mongod.conf中配置一个公共可访问接口:

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

相关问题