第 14 章 Spring Cache 缓存解决方案

1,Cache 介绍

Spring Cache 是一套框架缓存的解决方案,SpringBoot 有效的对 Cache 做出了简化,只需要使用注解即可操作我们保存在缓存区(包括内存区,缓存服务器Redis)的缓存数据(餐桌预定表,用户表)

应用系统需要通过 Cache 来缓存不经常改变的数据,以提高系统性能和增加系统吞吐量 。避免直接访问数据库等低速存储区系统 ,缓存的数据通常存放在访问速度更快的内存中或者是低延迟存取的存储器,服务器上 。

Spring Boot 集成 Cache 步骤如下

1,在 Maven 的 pom.xml 导入如下依赖

1 <!-- spring cache -->
2 <dependency>
3        <groupId>org.springframework.boot</groupId>
4        <artifactId>spring-boot-starter-cache</artifactId>
5 </dependency>

2,在 application.properties 中设置缓存中间件类型

1 <!-- 配置缓存中间价的类型 -->
2 spring.cache.type=redis (MonDB, Simple, none)

3,在启动类中开启 Cache

1 @EnableCaching
2 @SpringBootApplication
3 public class BookSystemMicroServices {
4     public static void main(String[] args) {
5         SpringApplication.run(BookSystemMicroServices.class, args);
6     }
7 }

2,注解驱动缓存

一旦配置好 SpringBoot 缓存,就可以在 Spring 管理的 Bean 中使用缓存注解,通常可以直接放在 Service 类方法上
  • @Cacheable  作用在方法上,触发缓存读取操作
  • @CacheEvict  作用在方法上,触发缓存失效操作
  • @CachePut  作用在方法上,触发缓存更新操作
  • @Cache  作用在方法上,综合上面的各种操作,在有场景下,调用业务会触发多种缓存操作
  • @CacheConfig  ,在类上设置当前缓存的一些公共设置

猜你喜欢

转载自www.cnblogs.com/zouzhu1998/p/12015952.html