Java連接虛擬機的redis報錯問題解決辦法

直奔主題,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服務,如下圖所示:



運行代碼,此時報錯如下:

[html] view plain copy
  1. <span style="color:#ff0000;">Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: </span>  
[html] view plain copy
  1. <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>  
[html] view plain copy
  1. <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>  
[html] view plain copy
  1. <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>  
[html] view plain copy
  1. <span style="color:#ff0000;">3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. </span>  
[html] view plain copy
  1. <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註釋了,爲何會報紅色的錯誤,經過網上查閱資料,發現其他網友也有類似問題,不過大部分人用的紅色報錯的第四種解決辦法,在這裏給出鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章