

实现SpringBoot + Redis缓存的源码与教程
source link: https://www.jdon.com/57033
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

总结了Redis的基础知识以及如何使用Redis在Spring Boot中集成缓存。
首先是依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
使用MySQL作为我的主要数据库,所以我使用 MySQL 连接器,还有 Spring Data Redis (access+driver) 依赖项在我们的项目中用作 Java Redis 客户端,这允许我们的应用程序启用 Redis 缓存机制。
现缓存时常用的注解如下:@CachePut、@CacheEvict、@Cacheable、@Caching,我们将看到我们在哪里以及如何使用这些注解。
@Entity public class User implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; private String email; private Integer age; public User() { super(); } public User(Integer id, String name, String email, Integer age) { super(); this.id = id; this.name = name; this.email = email; this.age = age; }
启用
@SpringBootApplication @EnableCaching public class RedisCacheApplication { public static void main(String[] args) { SpringApplication.run(RedisCacheApplication.class, args); } }
只要通过@EnableCaching注释启用缓存支持,Spring Boot 就会自动配置缓存基础结构。
查询
在控制器中,我们必须在每个 API 之上添加不同的注释来缓存特定记录。
@GetMapping("/{id}") @Cacheable(value= "Users", key="id") public User getUser(@PathVariable Integer id) { log.info(">> User Controller: get user by id: " + id); return userService.getUserById(id); }
在 GET 方法之上,我们使用@Cacheablewhich 表示每次调用该方法时,都会应用缓存行为,检查是否已经为给定的参数调用了该方法。
value="{category}"指定数据需要存储在哪个类别下。对于不同的控制器,我们可以使用不同的值。
一个合理的默认值只是使用方法参数来计算键,但我们也可以指定键以及使用key="#{value}"哪个将用于识别特定记录。
如果在缓存中找不到计算键或指定键的值,则将调用目标方法并将返回值存储在关联的缓存中。返回类型会自动处理,如果存在,它们的内容存储在缓存中。
保存
@PutMapping @CachePut(value="users", key="user", unless="result == null") public User updateUser(@RequestBody User user) { log.info(">> User Controller: update user: " + user.toString()); return userService.update(user); }
在PUT 方法之上,我们使用@CachePut. 我们也可以使用@CachePut本身来保存新用户,即POST 方法。
如果condition() 和unless() 表达式相应地匹配,则它始终会导致调用该方法并将其结果存储在关联的缓存中。Condition() 是 Spring 表达式语言 (SpEL) 表达式,用于有条件地进行缓存放置操作。由于 put 操作的性质,该表达式在调用方法后计算,因此可以引用方法的调用结果。
删除
@DeleteMapping("/{id}") @CacheEvict(value= "Users", allEntries = false, key="id") public void removeUser(@PathVariable Integer id) { log.info(">> User Controller: delete user: " + id); userService.delete(id); }
在 DELETE 方法之上,我们使用@CacheEvict它允许我们删除 Redis 中特定键的数据。allEntries指定是否应删除缓存中的所有条目。默认情况下,仅删除关联键下的值。请注意,不允许将此参数设置为 true 并指定键。
应用程序属性
我们可以通过不同的属性在我们的应用程序中配置 Redis 缓存,我使用了以下属性,如下所示:
spring.redis.host=localhost spring.redis.port=6379 spring.cache.redis.time-to-live=60000 spring.cache.cache-names=users,product,order
默认情况下,会根据需要创建缓存,但您可以通过设置该cache-names属性来限制可用缓存的列表。
我们可以用来在Spring中配置 Redis 缓存的属性如下所示:
要记住的要点
- 定义 TTLs :生存时间 (TTL),是您的缓存将删除条目的时间跨度。如果您只想每分钟获取一次数据,只需使用 @Cacheable Annotation 保护它并将 TTL 设置为 1 分钟。
- 实现 Serializable:如果你在 Redis 缓存中添加一个对象,那么该对象应该实现一个 Serializable 接口。
- Redis 缓存限制:当缓存大小达到内存限制时,旧数据将被删除,为新数据腾出空间。尽管 Redis 速度非常快,但在 64 位系统上存储任何数量的数据仍然没有限制。它只能在 32 位系统上存储 3GB 的数据。
- 永远不要从同一个类中调用可缓存方法:原因是 Spring 代理了对这些方法的访问,以使缓存抽象工作。当你在同一个类中调用它时,这个代理机制不会启动。通过这个,你基本上绕过了你的缓存并使其无效。
Recommend
-
14
Spring Boot 2.x基础教程:使用集中式缓存Redis 【福利时刻】关...
-
12
一、Android中的缓存策略一般来说,缓存策略主要包含缓存的添加、获取和删除这三类操作。如何添加和获取缓存这个比较好理解,那么为什么还要删除缓存呢?这是因为不管是内存缓存还是硬盘缓存,它们的缓存大小都是有限的。当缓存满了之后,再想其添加缓...
-
24
Redis源码阅读:RDB是怎么实现的 Redis中提供的另外一种持久化方式就是RDB,全称是 Redis Database,其实就是把Redis进程中存储的内容全部dump到 磁盘上,因此 RDB 文件是以二进制形式保存的,这一点与 AOF 相反。 在 Redis 中,我们可以通过...
-
11
Redis源码阅读:list实现(ziplist, quicklist) 如果我们用Redis做过broker,就知道,绝大部分的队列实现,都是基于 LPUSH 和 BRPOP 这两个命令的。那么,Redis到底是怎么 实现list的呢?底层是如何实现的,是否省内存,Red...
-
8
3【源码】数据可视化:基于 Echarts +Java SpringBoot 实现的动态实时大屏范例-物联网 ...
-
6
springboot(20)Redis缓存@Cacheable对存在的数据返回null 祈雨的博客 2018-06-08
-
4
图解 Kafka 源码实现机制之客户端缓存架构 作者:王江华 2022-09-23 08:02:42 今天主要聊聊 「Kafka 客户端消息缓存架构设计」,深度剖析下消息是如何进行缓存的。
-
3
1、五大基本数据类型和操作 1.1 字符串-string 命令 说明 set key value 如果key还没有,那就可以添加...
-
8
本文通过IDistributedCache的接口方法,实现Redis与MemoryCache统一帮助类。只需要在配置文件中简单的配置一下,就可以实现Redis与MemoryCache的切换。 IDistributedCache
-
11
源码分析 kubernetes apisix ingress crd 及缓存的实现原理 (二) 篇幅原因分成两个两篇, 第一篇主要分析了 apisix ingress controller 的架构实现以及对 k8s ingress 和 endpoints 进行分析.
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK