第一节:使用Jedis 连接Redis
新建maven项目:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cy</groupId> <artifactId>JedisDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> </dependencies> </project>
JedisTest.java:
package com.cy.test; import redis.clients.jedis.Jedis; public class JedisTest { public static void main(String[] args) { Jedis jedis = new Jedis("192.168.8.102", 6379); // 创建客户端 设置IP和端口 jedis.auth("123456"); // 设置密码 jedis.set("name", "Jedis测试"); // 设置值 String value = jedis.get("name"); // 获取值 System.out.println(value); jedis.close(); // 释放连接资源 } }
在测试过程中的报错以及解决办法:
报连接错误:Caused by: java.net.SocketTimeoutException: connect timed out,需要我们配置下防火墙 开一个6379端口权限
firewall-cmd --zone=public --add-port=6379/tcp --permanent
firewall-cmd --reload
报连接拒绝错误:Caused by: java.net.ConnectException: Connection refused: connect
需要编辑redis.conf ,将绑定本机bind 127.0.0.1注释掉;
[root@bogon redis]# vi /usr/local/redis/redis.conf
报连接错误:Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled
这个是因为远程连接redis redis自我保护 拒绝访问;
需要设置redis连接密码:
[root@localhost redis]# ./bin/redis-cli 127.0.0.1:6379> config set requirepass 123456 设置密码 123456 127.0.0.1:6379> quit [root@localhost redis]# ./bin/redis-cli 127.0.0.1:6379> get name (error) NOAUTH Authentication required. 127.0.0.1:6379> auth 123456 OK
第二节:Jedis 连接池使用
JedisPoolTest.java:
package com.cy.test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisPoolTest { public static void main(String[] args) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(100); //设置最大连接数 config.setMaxIdle(10); //设置最大空闲连接数 JedisPool jedisPool = new JedisPool(config, "192.168.8.102", 6379); Jedis jedis = null; try{ jedis = jedisPool.getResource(); jedis.auth("123456"); jedis.set("name", "Jedis测试2"); 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(); } } } }