Spring Cache集成redis的运行原理:
Spring缓存抽象模块通过CacheManager来创建、管理实际缓存组件,当SpringBoot应用程序引入spring-boot-starter-data-redi依赖后吗,容器中将注册的是CacheManager实例RedisCacheManager对象,RedisCacheManager来负责创建RedisCache作为缓存管理组件,由RedisCache操作redis服务器实现缓存数据操作。实际测试发现默认注入的RedisCacheManager操作缓存用的是RedisTemplate<Object, Object>,因此我们需要自定义cacheManager,替换掉默认的序列化器。
pom依赖
<!-- 引入redis启动依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 引入jedis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
代码层:service层
这里的缓存利用的是aop,所以我们需要在设置缓存的方法上返回对应的实体类数据,这样才能进行设置缓存
@CacheConfig(cacheNames = "userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
/**
* @Description: 新增设置缓存,并且返回值有值的情况下才进行设置
* condition = "#result!=nul 当返回结果有值的情况下,进行设置缓存
*/
@Override
// @CachePut(key = "'user:' + #user.id")
// @CachePut(key = "#root.methodName + '[' + #user.id + ']'" , condition = "#result!=null")
@CachePut(key = "'user:' + '[' + #user.id + ']'" , condition = "#result!=null")
public User insertData(User user) {
super.save(user);
return user;
}
/**
* @Description: Cacheable 注解,首次如果缓存中没有则会走数据库查询,查到数据之后会按照设置的key进行缓存数据
*/
// @Cacheable(key = "'user:' + #id")
@Cacheable(key = "'user:' + '[' + #id + ']'" )
public User getById(Long id){
System.err.println("没走缓存=============");
return super.getById(id);
}
/**
* CachePut 更新的时候更新数据库并且更新缓存数据,key值需要配置一致
*/
@CachePut(key = "'user:' + '[' + #user.id + ']'")
public User updateById1(User user){
System.out.println("走修改");
super.updateById(user);
return user;
}
/**
* 删除的时候直接根据key值删除
*/
// @CacheEvict(allEntries=true,beforeInvocation=true):代表清除所有缓存
@CacheEvict(key = "'user:' + '[' +#id+ ']'")
public Boolean delById(Long id){
System.out.println("走删除");
boolean b = super.removeById(id);
System.out.println(b);
return b;
}
key的命名规则:
@CacheConfig的cacheNames: + @Cacheable/@CachePut的key
如果设置完成之后发现缓存的key包含\xac\xed\x00\x05t\x00\tb这么多不友好的字符,出门左转:
https://blog.csdn.net/wwrzyy/article/details/85089463
Spring data 官方文档:https://docs.spring.io/spring-data/redis/docs/2.1.0.M1/api/