java连接mongod抛java.net.SocketTimeoutException: connect timed out异常(2015-11-07 20:29:58)

背景:本机的eclipse项目访问操作安装在本机虚拟机ContOS6.5系统上的MongoDB

最近在用java连接mongod的时候抛这个异常,后面发现是由于mongod的配置不对,一是mongod的配置文件中没有修改绑定的IP,使得外网无法访问。二是没有修改防火墙规则,27017端口没有对外开放。

com.mongodb.MongoSocketOpenException: Exception opening socket

    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)

    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)

    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)

    at java.lang.Thread.run(Thread.java:745)

Caused by: java.net.SocketTimeoutException: connect timed out

    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)

    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)

    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)

    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)

    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)

    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)

    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)

    at java.net.Socket.connect(Socket.java:589)

    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)

    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)

    ... 3 more

解决方法分两步

1、修改mongod的配置文件

#vi /etc/mongod.conf

修改

bindIp: 127.0.0.1 # Listen to local interface only, comment to listen on all interfaces.

bindIp: 192.168.5.128  # Listen to local interface only, comment to listen on all interfaces.

就是把本地IP改为服务器的IP,需要注意的是bindIp:后面有一个空格,修改后记得重启mongod

2、修改防火墙规则,增加27017端口

# vi /etc/sysconfig/iptables

增加-A INPUT -m state --state NEW -m tcp -p tcp --dport 27017 -j ACCEPT后重启防火墙即可。

你可能感兴趣的:(java连接mongod抛java.net.SocketTimeoutException: connect timed out异常(2015-11-07 20:29:58))