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