首先是打開遠程redis,我使用的是虛擬機centOS 6.4
然后下載jedis的jar包
連接:https://mvnrepository.com/artifact/redis.clients/jedis
測試代碼為:
import redis.clients.jedis.Jedis; public class MyJedis { public static void main(String[] args) { Jedis jedis = new Jedis("192.168.184.129",6379,10000); //Jedis jedis = new Jedis("localhost"); System.out.println("連接成功"); jedis.set("ylh", "ylh"); System.out.println(jedis.get("ylh")); } }
出現了如下錯誤:Caused by: java.net.SocketTimeoutException: connect timed out
原因是cenOS安裝默認打開防火牆
解決方案:
1. 在windows上ping Linux虛擬機的ip,測試連接 2. 檢查Linux下的防火牆是否關閉 用/ect/init.d/iptables status 查看防火牆狀態 用/etc/init.d/iptables stop 關閉防火牆
之后執行代碼出現如下錯誤
Exception in thread "main" 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. at redis.clients.jedis.Protocol.processError(Protocol.java:127) at redis.clients.jedis.Protocol.process(Protocol.java:161) at redis.clients.jedis.Protocol.read(Protocol.java:215) at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:340) at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:239)
解決方案:
vi redis.conf 1、修改redis服務器的配置文件 注釋以下綁定的主機地址 # bind 127.0.0.1 2、修改redis服務器的參數配置 修改redis的守護進程為no ,不啟用 daemonize no 修改redis的保護模式為no,不啟用 protected-mode no