redis在spring中的Cache应用

1.大家可以先看一下Spring之缓存注解@Cacheable https://blog.csdn.net/My_blankness/article/details/80988308
2.redis的缓存一般在service层配置。当访问改方法时,会先查找是否有该key的Cache,有的话,直接返回,没有的话,数据库查询出来,并且存入缓存中。
@Cacheable(“getUserById”) //标注该方法查询的结果进入缓存,再次访问时直接读取缓存中的数据

@Override
public User getUserById(int userId) {
return this.iUserDao.selectByPrimaryKey(userId);
}
或者
@Cacheable(cacheNames = “getUserById”, key = “#userId+ ‘’”, unless="#result == null")
@Override
public User getUserById(int userId) {
return this.iUserDao.selectByPrimaryKey(userId);
}
当调用这个方法的时候,会从一个名叫 getUserById的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。这里的缓存中的 key 就是参数 userId,value 就是 User 对象。

有添加进缓存,必定有删除缓存,所以在更新,删除或者插入方法时,就要使用CacheEvict来删除缓存。

 @CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true)
    @Override
    public void editUser(User user) {
        this.iUserDao.editUser(user);
    }

表示清空这三个方法的所有缓存。
参考的博客有
https://www.cnblogs.com/hello-daocaoren/p/7891907.html
https://blog.csdn.net/My_blankness/article/details/80988308

猜你喜欢

转载自blog.csdn.net/lkpklpk/article/details/82824444