测试缓存:
原理:
CacheManager===Cache 缓存组件来实际给缓存中存储数据
1,引入redis的starter,容器中保存的是RedisCacheManager
2,RedisCacheManager 帮我们创建RedisCache 来作为缓存组件;
RedisCache通过操作redis来缓存数据
3,默认保存数据 K -V 都是通过序列化来保存的;
关于能存储redis。第二次查不能反序列化出来的问题。
原因:存的是dept的缓存数据,而CacheManager默认使用RedisTemplate<Object, Employee>来操作redis
解决方法:
自定义CacheManager:
1> 引入了redis的starter,cacheManager变为RedisCacheManager
2> 默认创建的RedisCacheManager 操作redis的时候使用的是 RedisTemlate<Object,Object>
3> RedisTemlate<Object,Object> 是默认使用jdk序列化机制
4> 自定义CacheManager
@Configuration
public class MyRedisConfig { //员工缓存
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(ser);
return template;
} //员工缓存
//CacheManagerCustomizers 可以定制缓存的一些规则
@Bean
@Primary //默认缓存管理器 必须得有默认
public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
//key多了一个前缀 //使用前缀,默认把cacheName作为前缀
cacheManager.setUsePrefix(true);
return cacheManager;
} //部门缓存
@Bean
public RedisTemplate<Object, Department> deptRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Department> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Department> ser = new Jackson2JsonRedisSerializer<Department>(Department.class);
template.setDefaultSerializer(ser);
return template;
} //部门缓存
@Bean
public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> deptRedisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(deptRedisTemplate);
cacheManager.setUsePrefix(true);
return cacheManager;
}
}
- @Primary 当自定义两个CacheManager的时候。必须指定一个为默认的
- 针对不同的service可以直接标注CacheManager,同时如果有默认指定,可以省略不写
@CacheConfig(cacheNames = "dept",cacheManager = "deptCacheManager")
@Service
public class DeptService {@CacheConfig(cacheNames = "emp"/*,cacheManager = "employeeCacheManager"*/)
@Service
public class EmployeeService { - 以上都是注解形式的缓存,编码形式的缓存写法:
//方法内,编码方式做缓存
@Qualifier("deptCacheManager")
@Autowired
RedisCacheManager deptCacheManager; //在方法内做缓存写法
public Department getDeptById(Integer id){
System.out.println("查询部门id为"+id+"...........");
Department dept = departmentMapper.getDeptById(id);
Cache deptCache=deptCacheManager.getCache("dept");//相当于 @Cacheable(cacheNames = "dept")
deptCache.put("dept:1",dept);
return dept;
}