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

林家小米發表於2016-08-22

直奔主題,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註釋了,為何會報紅色的錯誤,經過網上查閱資料,發現其他網友也有類似問題,不過大部分人用的紅色報錯的第四種解決辦法,在這裡給出連結


相關文章