1. 程式人生 > >使用Jedis 連線 Redis 時可能出現的常見錯誤

使用Jedis 連線 Redis 時可能出現的常見錯誤

本人作為一個初學者學習Redis的使用,遇到了下面一些異常,總結了一些解決方案。

1、SocketTimeoutException 連線超時

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: connect timed out

這種情況先排除是否開啟了redis,或者ip地址和埠是否書寫正確。如果沒有以上問題,那必定是防火牆未允許Redis的預設埠 6379。

編輯防火牆配置檔案 :vim /etc/sysconfig/iptables

新增紅框標註語句,儲存並退出。重啟防火牆:service iptables restart

2、Connection refused 拒絕訪問

Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect

修改redis.conf配置檔案,使用vim命令開啟。


找到bind那行用#號註釋,儲存並退出,重啟redis-server。

3、JedisDataException:DENIED Redis is running in protected mode 保護模式

redis.clients.jedis.exceptions.JedisDataException: 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: 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. 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. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 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.

這個異常主要是說redis開啟了protected mode,這也是Redis3.2加入的新特性,開啟保護模式的redis只允許本機登入,同樣在配置檔案redis.conf中,如下圖


這裡原來預設是yes,代表開啟了保護模式,後面可以填密碼也可以填no代表關閉,我們這裡選擇關閉保護模式,儲存退出後再重啟redis-server。

以上都是本人親測解決方案,借鑑了https://www.jianshu.com/p/2fa4622fc1d3,歡迎指點。