2.3.4 @Caching注释
在使用缓存的时候,有可能会同时进行更新和删除,会出现同时使用多个注解的情况.而@Caching可以实现,对于复杂的缓存策略,我们可借助SpEL实现;
Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:
其它:==如果表达式想直接引用一个常量值,那么需要 key="'xxxx'"==
示例代码:
@Caching(
cacheable = {
@Cacheable(key = "#role.rolename")
},
put = {
@CachePut(key = "#role.id"), @CachePut(key = "#role.rolecode")
},
evict = {
@CacheEvict(key = "5")
}
)
@Override
public R add(Role role) {
try {
roleMapper.insert(role);
} catch (Exception e) {
return R.error();
}
return R.ok(role.getId());
}
测试代码
/**
* @Description 测试@Caching复合缓存操作
*/
@Test
public void testCaching(){
Role role = Role.builder().id(15).rolecode("015").rolename("015Role").introduce("015Introduce").build();
roleService.add(role);
}
运行测试方法前查看缓存数据
运行完测试方法后查看redis数据