Spring boot + Redis + Spring Cache 实现缓存

学习

Redis 的 value 有 5 种常用的数据结构

Redis 存储的是 key-value 结构的数据。key 是字符串类型,value 有 5 种常用的数据结构:

Redis 的图形化工具

Another Redis Desktop Manager

Spring Data Redis

Redis 的 Java 客户端。

Spring Cache

Spring Cache 是一个框架,基于注解实现缓存功能,更加简单。底层的缓存实现,可以是Redis、Caffeine或者EHCache等。

Spring Cache 常用注解:

配置

  1. 下载Redis。(默认没有密码)
  2. 在 xml 中引入 Spring Data Redis 和 Spring Cache 2.7.3 的依赖。
  3. 在 yml 中配置 Redis 数据源。

实现

1. 开启:@EnableCaching

放在启动类上,开启缓存注解功能。

2. 增:@CachePut

在 Controller 层:

java 复制代码
//    增
    @PostMapping()
    @CachePut(cacheNames = "userCache", key = "#user.id")  // key = userCache::id
    public User save(@RequestBody User user) throws IOException {
//        保存到mysql
        userService.save(user);
//        保存到mysql后,id已经有了,可以直接插入到ES
        esService.AddDocument(user);
        return user;
    }

采用了spEL表达式(#对象.属性)。

注:先操作 save 方法,再操作 @CachePut,所以 user 此时有 id 了。

3. 查:@Cacheable

4. 删、改:@CacheEvict

  1. @CacheEvict(cacheNames = "userCache", key = "#user.id") 删除某个id
  2. @CacheEvict(cacheNames = "userCache", allEntries = True) 删除所有
相关推荐
大可不必了2 小时前
03 函数定义和调用
开发语言·python
I_belong_to_jesus2 小时前
C++关于分支预测的优化1
开发语言·c++·算法
承渊政道3 小时前
【Python编程—从入门到实践】(记分与闯关:用Python+Pygame,打造越战越精彩的太空大战!)
开发语言·python·pycharm·游戏程序·pygame
爱学习的程序媛3 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
budingxiaomoli4 小时前
Spring统一功能处理
java·后端·spring
eggwyw4 小时前
Anaconda安装卸载的详细流程指南
开发语言·python
Flynn Liang6 小时前
可观测性与成本治理:一次对话的 17 个观测点
java·langchain·可观测性·micrometer·langchain4j·token 成本·llm 监控
金銀銅鐵6 小时前
带您看懂字节码指令(三):同一行加法,为什么有四种指令
java·jvm
another heaven9 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
文丑颜不良啊10 小时前
LeetCode2821~2840题目解析
java·leetcode