Spring Cache学习笔记 | 青训营笔记

118 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 8 天

前面学习了许多redis的相关知识,本节学习和记录一款缓存框架--Spring Cache。使用起来,我个人觉得非常的方便。

什么是Spring Cache

Spring Cache是一个框架,基于注解实现了缓存功能,只需要在方法上加一个注解,就能实现缓存功能。Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。CacheManager是Spring提供的各种缓存技术抽象接口。

针对不同的缓存技术需要实现不同的CacheManager:

CacheManager描述
EhCacheCacheManager使用EhCache作为缓存技术
GuavaCacheManager使用Google的GuavaCache作为缓存技术
RedisCacheManager使用Redis作为缓存技术

常用注解

  • @EnableCaching
    • 开启缓存注解功能,一般放在启动类上
  • @Cacheable
    • spring查看缓存中是否有数据 ? 直接返回数据 : 调用方法并将方法返回值放到缓存中
    • 属性
      • condition:满足条件时缓存
      • unless:满足条件是不缓存
  • @CachePut
    • 将方法的返回值放到缓存中
    • 属性
      • value:缓存的名称,用于区分一类数据,每个缓存名称下面可以有多个key
      • key:缓存的key
        • #result:方法的返回值
        • #root:修饰的方法
        • #<methodValue>:方法的参数
  • @CacheEvict
    • 将一条或多条数据从缓存中删除
    • 属性
      • value:缓存的名称,用于区分一类数据,每个缓存名称下面可以有多个key
      • key:缓存的key
      • allEntries:true/fales,是否清理分类下所有缓存数据

使用redis

  1. 引入依赖
<!-- Redis -->
<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Spring Cache -->
<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
  1. yml配置
spring:
	redis:
    database: 1
    host: 127.0.0.1
    port: 6379
    password: 
  cache:
    redis:
      time-to-live: 180000 # 设置过期时间,单位/ms
  1. 启动类加入@EnableCaching注解,开启缓存注解功能
  2. 注入
@Autowired
private CacheManager cacheManager;
  1. 正常crud