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) 删除所有
相关推荐
Flynn Liang2 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio3 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易3 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设
文丑颜不良啊3 小时前
LeetCode3041~3060题目解析
java·leetcode
eggwyw3 小时前
C++ union 的一种妙用法
开发语言·c++
文丑颜不良啊4 小时前
LeetCode3101~3120题目解析
java·leetcode
Resean02235 小时前
SpringMVC 6+源码分析(十一)视图渲染与异步请求(收尾篇)
java·spring·springmvc
starzy19905 小时前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
靠沿5 小时前
MySQL数据库进阶——存储过程和触发器
java·数据库·mysql
码少女6 小时前
MySQL--库与表的增删改查基础
java·数据库·mysql