直奔主题,Java连接虚拟机报错,代码如下:
public class TestPing {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.201.128", 6379);
System.out.println(jedis.ping());
}
}
运行报错,控制台信息如下:
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: connect timed out
借鉴一些网友的解决方案:
关闭虚拟机的防火墙
1)暂时关闭防火墙:/etc/init.d/iptables stop
2) 重启虚拟机生效:chkconfig iptables off 或者 /sbin/chkconfig --level 2345 iptables off
楼主使用的是第二种方法,如下图所示:
重启虚拟机之后,在查看防火墙状态,如下图所示
继续运行上述代码,报错如下:
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
解决方案,修改redis.conf配置文件,将端口号127.0.0.1注释掉,这样任何IP都能访问,如下图所示:
保存退出后,运行代码,发现报错依旧,因为尚未启动redis服务,启动redis服务,如下图所示:
运行代码,此时报错如下:
- <span style="color:#ff0000;">Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: </span>
- <span style="color:#ff0000;">DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: </span>
- <span style="color:#ff0000;">1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. </span>
- <span style="color:#ff0000;">2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. </span>
- <span style="color:#ff0000;">3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. </span>
- <span style="color:#ff0000;">4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.</span>
上述exception大致意思是:拒绝redis在保护模式下运行的,没有绑定IP地址,没有授权密码,如果你想从外部电脑连接redis的话,你必须要采纳以下其中的某一个解决方法
楼主采用的第二种方法,修改redis.conf配置文件,将protected-mode yes 改为no,如下图所示
重启虚拟机,启动redis服务,如下图所示
运行代码,控制台输出PONG,如下图所示:
到此,问题解决。
题外话:我有个疑问就是防火墙和redis.conf配置文件里已经把IP注释了,为何会报红色的错误,经过网上查阅资料,发现其他网友也有类似问题,不过大部分人用的红色报错的第四种解决办法,在这里给出链接