建立一個maven項目
pom文件如下:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
測試類代碼
public class TestJedis {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.1.10",6379);
jedis.set("name", "Jedis Redis");
String value=jedis.get("name");
System.out.println(value);
jedis.close();
}
}
首先啓動redis 服務
運行代碼報錯 報出connet time out 異常
是因爲防火牆6379端口沒有開權限,運行下述代碼進行開權限:
firewall-cmd –zone=public –add-port=6379/tcp –permanent
firewall-cmd –reload
然後運行 還是報錯:
這裏綁定了本機 我們要註釋掉
修改完配置 保存 重啓redis:
[root@localhost redis]# ./bin/redis-cli shutdown
[root@localhost redis]# ./bin/redis-server ./redis.conf
然後運行代碼又報錯:
這是因爲遠程連接redis redis自我保護 拒絕訪問;
這裏有兩種解決方法;
第一種 關閉自我保護功能(開發中不推薦)
root@localhost redis]# vi /usr/local/redis/redis.conf
進入配置
找到 protected-mode yes
改成 no即可
第二種 設置Redis連接密碼
進入客戶端
保證Redis啓動
[root@localhost redis]# ./bin/redis-server ./redis.conf
[root@localhost redis]# ./bin/redis-cli
127.0.0.1:6379> config set requirepass 123456
OK
127.0.0.1:6379>
Ctrl+c退出
[root@localhost redis]# ./bin/redis-cli
127.0.0.1:6379> auth 123456
OK
說明設置成功
然後在測試代碼中加入jedis.auth(“123456”);
運行得到如下結果:
下面說下redisPool連接池的用法:
測試代碼如下:
public class TestJedis {
public static void main(String[] args) {
JedisPoolConfig jpconfig= new JedisPoolConfig();//初始化連接池
jpconfig.setMaxTotal(100);//設置最大連接數
jpconfig.setMaxIdle(10);//設置最大空閒連接數
JedisPool jedisPool = new JedisPool(jpconfig,"192.168.1.10",6379);
Jedis jedis=null;
try{
jedis=jedisPool.getResource();
jedis.auth("123456");
jedis.set("name", "Jedis Redis");
String value=jedis.get("name");
System.out.println(value);
}catch(Exception e){
e.printStackTrace();
}finally{
if(jedis!=null){
jedis.close();
}
if(jedisPool!=null){
jedisPool.close();
}
}
}
}
測試結果: