springboot集成caffice

springboot集成caffice



需要引入两个包,如下:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
  <groupId>com.github.ben-manes.caffeine</groupId>
  <artifactId>caffeine</artifactId>
</dependency>

在配置文件里添加

笔记插图(第 1 页)

Caffeine常用配置说明:

initialCapacity=[integer]: 初始的缓存空间大小

maximumSize=[long]: 缓存的最大条数

maximumWeight=[long]: 缓存的最大权重

expireAfterAccess=[duration]: 最后一次写入或访问后经过固定时间过期

expireAfterWrite=[duration]: 最后一次写入后经过固定时间过期

refreshAfterWrite=[duration]: 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存

注意点:

expireAfterWrite和expireAfterAccess同事存在时,以expireAfterWrite为准

maximumSize和maximumWeight不可以同时使用

在启动类上加上:@EnableCaching

笔记插图(第 2 页)

使用缓存有两种方法:

(1)、注解

(2)、代码方式(注掉代码)

例如:

笔记插图(第 2 页)