基本原理:
CacheManager===Cache 緩存組件來實際給緩存中存儲數(shù)據(jù)
1.引入redis的starter午衰,容器中保存的是RedisCacheManager
2.RedisCacheManager 幫我們創(chuàng)建RedisCache 來作為緩存組件
RedisCache通過操作redis來緩存數(shù)據(jù)
3.默認保存數(shù)據(jù) K -V 都是通過序列化來保存的
關(guān)于能緩存數(shù)據(jù)到redis昂验,第二次查不能反序列化出來的問題。
原因:存的是dept的緩存數(shù)據(jù)赛惩,而CacheManager默認使用RedisTemplate<Object, Employee>來操作redis手蝎。
解決方法:
自定義CacheManager:
- 引入了redis的starter,cacheManager變?yōu)镽edisCacheManager
- 默認創(chuàng)建的RedisCacheManager 操作redis的時候使用的是 RedisTemlate<Object雄嚣,Object>
- RedisTemlate<Object晒屎,Object> 是默認使用jdk序列化機制
- 自定義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 可以定制緩存的一些規(guī)則
@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;
}
}
- 總結(jié):
1.@Primary 當自定義兩個CacheManager的時候,必須指定一個為默認的鼓鲁。
2.針對不同的service可以直接標注CacheManager履肃,同時如果有默認指定,可以省略不寫坐桩。
@CacheConfig(cacheNames = "dept",cacheManager = "deptCacheManager")
@Service
public class DeptService {
@CacheConfig(cacheNames = "emp"/*,cacheManager = "employeeCacheManager"*/)
@Service
public class EmployeeService {
3.以上都是注解形式的緩存尺棋,編碼形式的緩存寫法。
//方法內(nèi)绵跷,編碼方式做緩存
@Qualifier("deptCacheManager")
@Autowired
RedisCacheManager deptCacheManager;
//在方法內(nèi)做緩存寫法
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;
}