基于RedisTemplate+Jedis的数据操作
前言
Redis是最常用的KV数据库,Spring 通过模板方式(RedisTemplate)提供了对Redis的数据查询和操作功能。
一、Redis基础和数据结构
首先对于Redis来说,所有的Key都是字符串。我们谈论数据结构时,谈论的是值(value)的数据结构,主要包括常见的五种:String,List,Set,Zset,Hash。
什么是Jedis
Jedis是Redis的Java客户端,在Spring boo1.x版本中也是默认的客户端。在SpringBoot 2.x版本中默认客户端是Luttuce
Spring中的Template和RedisTemplate
Spring 通过模板方式(RedisTemplate)提供了对Redis的数据查询和操作功能。
什么是模板模式?
模板方法模式(Template pattern): 在一个方法中定义一个算法的骨架, 而将一些步骤延迟到子类中. 模板方法使得子类可以在不改变算法结构的情况下, 重新定义算法中的某些步骤。
RedisTemplate对于Redis5种基础类型的操作?
redisTemplate.opsForValue(); // 操作字符串
redisTemplate.opsForHash(); // 操作hash
redisTemplate.opsForList(); // 操作list
redisTemplate.opsForSet(); // 操作set
redisTemplate.opsForZSet(); // 操作zset
二、集成Redis
包依赖
引入spring-boot-starter-data-redis包,SpringBoot2中默认的客户端是Lettuce, 所以需要exclude掉lettuce-core包,并引入jedis的包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<artifactId>lettuce-core</artifactId>
<groupId>io.lettuce</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.9.0</version>
</dependency>
yml配置
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
password: test
jedis:
pool:
min-idle: 0
max-active: 8
max-idle: 8
max-wait: -1ms
connect-timeout: 30000ms
RedisConfig配置
package tech.pdai.springboot.redis.jedis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis configuration.
*
*/
@Configuration
public class RedisConfig {
/**
* redis template.
*
* @param factory factory
* @return RedisTemplate
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}