@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate
常用注解
@Cacheable
如果缓存中有数据,直接返回结果
如果没有数据,查询数据库,返回结果
// @Cacheable(keyGenerator = "myKeyGenerator",key = "findAllRole")
@Cacheable(key = "#root.method.getName()")
@Override
public CommonResult findAllRole() {
List roleList = roleMapper.findAll();
return CommonResult.success(roleList);
}
}
@CacheEvict注解
@CacheEvict:删除缓存的注解,这对删除旧的数据和无用的数据是非常有用的。这里还多了一个参数(allEntries),设置allEntries=true时,可以对整个条目进行批量删除。
@Override
@CacheEvict(key = "#id")
public Integer delete(Integer id) {
return roleMapper.deleteByPrimaryKey(id);
}
@CachePut注解
@CachePut:当需要更新缓存而不干扰方法的运行时 ,可以使用该注解。也就是说,始终执行该方法,并将结果放入缓存
@Override
@CachePut(key = "#result.id")
public Role update(Role role) {
roleMapper.updateByPrimaryKey(role);
return role;
}
@Caching注释
在使用缓存的时候,有可能会同时进行更新和删除,会出现同时使用多个注解的情况.而@Caching可以实现``
//添加user缓存的同时,移除userPage的缓存
@Caching(put =@CachePut(value = "user",key ="#userVo.id"),
evict = @CacheEvict(value = "userPage",allEntries = true))