前言
主要是对于自己学习以及熟悉redis的使用为目的,对此进行整理
springboot2.x整合redis。其中Jedis 和 Lettuce 是 Java 操作 Redis 的客户端。在 Spring Boot 1.x 版本默认使用的是 jedis ,而在 Spring Boot 2.x 版本默认使用的就是Lettuce。关于 Jedis 跟 Lettuce 的区别如下:
- Jedis在实现上是直接连接的redis server,如果在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接
- Lettuce的连接是基于Netty的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,应为StatefulRedisConnection是线程安全的,所以一个连接实例(StatefulRedisConnection)就可以满足多线程环境下的并发访问,当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。
参考:https://www.jianshu.com/p/071bae3834b0
https://www.cnblogs.com/mzq123/p/8036914.html
一、Redis介绍
1.Redis简介
官方给出的定义是:
- Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。
- 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。
- Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions)
- 提供不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)
2.为什么使用Redis
数据查询每次都需要从数据库中查询数据,数据库压力会很大,查询速度过慢,因此设置缓存层,查询数据时先从redis 中查询,如果查询不到,则到数据库中查询,然后将查出的数据备份到redis中一份,这样下次查询的时候可以直接从redis 中读取,不需要在查询数据库了,减少了数据库的压力,而且redis查询速度快。
参考:https://blog.csdn.net/m0_38084895/article/details/82900686
3.Redis数据结构操作
博客:https://my.oschina.net/u/3343218/blog/2989564#h3_2
二、示例
示例是有maven搭建的
2.1依赖
在pom.xml中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.2配置文件
此处采用的是yml格式,配置如下:
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password:
max-active: 200 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
timeout: 1000 # 连接超时时间(毫秒)
2.3 redisTemplate配置
2.3.1 redisTemplate自动配置
在引入redis的依赖后,redisTemplate会自动配置,可以直接注入使用redisTemplate模板。
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
springboot帮我们生成了两个模板,redisTemplate和stringRedisTemplate。但是可以看到RedisTemplate的泛型是<Object,Object>,这样不便于我们操作,会造成多次转换的问题。
因为有@ConditionalOnMissingBean(name = "redisTemplate")注解,所以如果spring的容器中有一个name为redisTemplate实例,name这个自动配置的redisTemplate模板就不会实例化。
2.3.2redis对象序列化操作类
- 正常redis的key都是string类型,所以我们需要一个<String,Object>泛型的redisTemplate模板,使用redisTemplate存储数据到Redis时的key和value的序列化方式默认使用JdkSerializationRedisSerializer,这样的会导致我们通过redis desktop manager显示的我们key跟value的时候显示不是正常字符
- 对象 的序列化保存问题,毕竟 Redis 数据库的读写速度是非常快的,但是如果不能够进行对象的存储,这样的存储意义就不大了,这样 就需要准备一个对象的序列化处理程序类,通过对象的形式进行数据的存储。
package springboot.example.redis.configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
/**
* 此时定义的序列化操作表示可以序列化所有类的对象,当然,这个对象所在的类一定要实现序列化接口
*/
public class RedisObjectSerializer implements RedisSerializer<Object>{
//为了方便进行对象与字节数组的转换,所以应该首先准备两个转换器
private Converter<Object, byte[]> serializingConverter = new SerializingConverter();
private Converter<byte[], Object> deserializingConverter = new DeserializingConverter();
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; //做一个空数组,不是null
@Override
public byte[] serialize(Object t) throws SerializationException {
if(t == null){ //此时没有要序列化的对象出现,所以返回字节数组应该是一个空数组
return EMPTY_BYTE_ARRAY;
}
return this.serializingConverter.convert(t);
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if(bytes == null || bytes.length == 0){ //此时没有对象的内容信息
return null;
}
return this.deserializingConverter.convert(bytes);
}
}
2.3.3配置Redis
package springboot.example.redis.configuration;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/**
* redis配置类
* 1.创建redis模板
* 2.序列化redis数据
*/
@Configuration
public class RedisAutoConfiguration {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
/*
* 序列化
* 1.用jackson
*/
// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
// ObjectMapper om = new ObjectMapper();
// om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
// om.enableDefaultTyping(DefaultTyping.NON_FINAL);
// jackson2JsonRedisSerializer.setObjectMapper(om);
/*
* 2.自定义
*/
RedisObjectSerializer redisObjectSerializer = new RedisObjectSerializer();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用String序列化
template.setKeySerializer(stringRedisSerializer);
//hash的key也用String序列化
template.setHashKeySerializer(stringRedisSerializer);
//value采用jackson序列化方式
template.setValueSerializer(redisObjectSerializer);
//hash的value也采用jackson序列化方式
template.setHashValueSerializer(redisObjectSerializer);
template.afterPropertiesSet();
return template;
}
}
注意:方法名一定要叫redisTemplate 因为@Bean注解是根据方法名配置这个bean的name的,覆盖默认配置
3.redis缓存处理
3.1定义元注解
package springboot.example.redis.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 用于方法,对当前方法表示是否开启缓存
* Created by Lich
*
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface NeteaseEduCache {
String key();
}
3.2 Spring AOP实现监控所有被@NeteaseEduCache注解的方法缓存
先从Redis里获取缓存,查询不到,就查询MySQL数据库,然后再保存到Redis缓存里,下次查询时直接调用Redis缓存
package springboot.example.redis.annotation;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import springboot.example.redis.utils.RedisUtils;
/**
* 缓存注解解析类
* Created by Lich.
*
*/
@Component
@Aspect
public class CacheAdvisor {
private static final Logger log = LoggerFactory.getLogger(CacheAdvisor.class);
@Pointcut("@annotation(springboot.example.redis.annotation.NeteaseEduCache)")
private void pointCut(){
}
@Around("pointCut()")
public Object queryCache(ProceedingJoinPoint pjp) throws Throwable {
log.info("**********方法执行前增强***************");
long startTime = System.currentTimeMillis();
// 获取方法上的注解key的值
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
NeteaseEduCache neteaseEduCache = method.getAnnotation(NeteaseEduCache.class);
String keyEL = neteaseEduCache.key();
log.info("************获取到el表达式的keyEL*********");
log.info("keyEL表达式:" + keyEL);
/*
* 获取EL表达式所需,方法调用参数---------方法的参数名及参数 1.创建解析器
*/
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(keyEL);
/*
* 2.设置解析上下文(有哪些占位符,以及每种占位符的值)
*/
EvaluationContext context = new StandardEvaluationContext(); // 方法的参数名和参数值
Object[] args = pjp.getArgs(); // 参数值
String[] parameterNames = new DefaultParameterNameDiscoverer().getParameterNames(method); // 参数名
for (int i = 0; i < args.length; i++) {
context.setVariable(parameterNames[i], args[i]);
}
/*
* 3.解析得到一个key
*/
String key = expression.getValue(context).toString();
Object object = RedisUtils.get(key);
if (null != object) {
log.info("**********从Redis中查到了数据**********");
log.info("Redis的KEY值:" + key);
log.info("Redis的VALUE值:" + object.toString());
return object;
}
long endTime = System.currentTimeMillis();
log.info("Redis缓存AOP处理所用时间:" + (endTime - startTime));
log.info("**********没有从Redis查到数据**********");
try {
object = pjp.proceed();
} catch (Exception e) {
e.printStackTrace();
}
log.info("**********方法执行后增强***************");
log.info("**********开始从MySQL查询数据**********");
/*
* 后置:将数据库查到的数据保存到Redis
*/
boolean isSave = RedisUtils.set(key, object);
if (isSave) {
log.info("**********数据成功保存到Redis缓存!!!**********");
log.info("Redis的KEY值:" + key);
log.info("REDIS的VALUE值:" + object.toString());
}
return object;
}
}
3.3 service实现
package springboot.example.service.redis;
import org.springframework.stereotype.Service;
import springboot.example.redis.annotation.NeteaseEduCache;
@Service
public class RedisService {
@Autowired
private MybatisMapper mybatisMapper;
@NeteaseEduCache(key = "#name")
public String getValue(String id,String name){
return mybatisMapper.selectAll();
}
}
3.4 controller实现
package springboot.example.controller.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springboot.example.service.redis.RedisService;
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisService redisService;
@RequestMapping("test")
public String redisTest(String id,String name){
return redisService.getValue(id,name);
}
}