导入依赖:
<!-- jedis依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
jedis包的版本一定要是3.0.0以上,否则用SpringBoot整合redis可能会报错。虽然4.0以上的版本已经出来了,但还是建议使用3.x的版本。
在命令行打开redis服务:
redis-server redis.conf
在java代码中直接使用Jedis类来redis数据库:
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.set("name", "ruby");
Set<String> keys = jedis.keys("*");
System.out.println(keys);
for (String key : keys) {
System.out.println(jedis.get(key));
}
jedis.close();
以上是测试代码,最终执行成功
jedis对象还可以调用sadd、hset等方法这是其他数据结构。
还可以使用连接池的技术进行连接:
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(200); // 最大连接数
jedisPoolConfig.setMaxIdle(32); // 最大空闲连接数
jedisPoolConfig.setMaxWaitMillis(100 * 1000); //最大等待时间
jedisPoolConfig.setBlockWhenExhausted(true); //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
jedisPoolConfig.setTestOnBorrow(true); //在获取连接的时候检查有效性
JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
Jedis jedis = jedisPool.getResource();
jedis.set("name", "ruby");
Set<String> keys = jedis.keys("*");
System.out.println(keys);
for (String key : keys) {
System.out.println(jedis.get(key));
}
jedis.close();
关于连接池的一些更加详细的配置,可以参考redis-JedisPoolConfig配置
下面介绍SpringBoot整合redis,会涉及到很多坑。在以上依赖的基础上继续引入依赖:
<!-- springboot整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
<exclusion>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</exclusion>
</exclusions>
</dependency>
引入该依赖一定要排除letture-core的jar包,否则会报错:Cannot resolve org.reactivestreams:reactive-streams:1.0.3。然后还要排除自身的jedis的jar包,因为版本不兼容的问题,一定要确保使用文章最开始引入的jedis jar包。这里SpringBoot的版本是2.2.3。各个jar包之间的版本问题可详见SpringBoot整合Spring Data Redis和Jedis报错。
然后在配置文件中进行一些配置:
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
#连接超时时间
spring.redis.timeout=1800000
#最大连接数
spring.redis.jedis.pool.max-active=20
#最大阻塞等待时间,-1表示没限制
spring.redis.jedis.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=5
#连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
然后就可以在java代码中直接使用RedisTemplate:
@Autowired
RedisTemplate redisTemplate;
@Test
public void redisTemplateTest() {
redisTemplate.opsForSet().add("name", "lucy", "ruby", "jack");
System.out.println(redisTemplate.opsForSet().members("name"));
}
RedisTemplate使用opsForValue操作一般的字符串类型数据,使用opsForSet操作集合,使用opsForList操作列表,等等。