服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring Boot缓存实战 Caffeine示例

Spring Boot缓存实战 Caffeine示例

2021-04-07 14:28xiaolyuh Java教程

本篇文章主要介绍了Spring Boot缓存实战 Caffeine示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

CaffeineSpring Boot集成

Caffeine是使用Java8对Guava缓存的重写版本,在Spring Boot 2.0中将取代Guava。如果出现Caffeine,CaffeineCacheManager将会自动配置。使用spring.cache.cache-names属性可以在启动时创建缓存,并可以通过以下配置进行自定义(按顺序):

  • spring.cache.caffeine.spec: 定义的特殊缓存
  • com.github.benmanes.caffeine.cache.CaffeineSpec: bean定义
  • com.github.benmanes.caffeine.cache.Caffeine: bean定义

例如,以下配置创建一个foo和bar缓存,最大数量为500,存活时间为10分钟:

?
1
2
spring.cache.cache-names=foo,bar
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

除此之外,如果定义了com.github.benmanes.caffeine.cache.CacheLoader,它会自动关联到CaffeineCacheManager。由于该CacheLoader将关联被该缓存管理器管理的所有缓存,所以它必须定义为CacheLoader<Object, Object>,自动配置将忽略所有泛型类型。

引入依赖

?
1
2
3
4
5
6
7
8
9
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
  <groupId>com.github.ben-manes.caffeine</groupId>
  <artifactId>caffeine</artifactId>
  <version>2.6.0</version>
</dependency>

开启缓存的支持

使用@EnableCaching注解让Spring Boot开启对缓存的支持

?
1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableCaching// 开启缓存,需要显示的指定
public class SpringBootStudentCacheCaffeineApplication {
 
  public static void main(String[] args) {
    SpringApplication.run(SpringBootStudentCacheCaffeineApplication.class, args);
  }
}

配置文件

新增对缓存的特殊配置,如最大容量、过期时间等

?
1
2
spring.cache.cache-names=people
spring.cache.caffeine.spec=initialCapacity=50,maximumSize=500,expireAfterWrite=10s,refreshAfterWrite=5s

如果使用了refreshAfterWrite配置还必须指定一个CacheLoader,如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * 必须要指定这个Bean,refreshAfterWrite=5s这个配置属性才生效
 *
 * @return
 */
@Bean
public CacheLoader<Object, Object> cacheLoader() {
  CacheLoader<Object, Object> cacheLoader = new CacheLoader<Object, Object>() {
 
    @Override
    public Object load(Object key) throws Exception {
      return null;
    }
 
    // 重写这个方法将oldValue值返回回去,进而刷新缓存
    @Override
    public Object reload(Object key, Object oldValue) throws Exception {
      return oldValue;
    }
  };
  return cacheLoader;
}

Caffeine配置说明:

  1. initialCapacity=[integer]: 初始的缓存空间大小
  2. maximumSize=[long]: 缓存的最大条数
  3. maximumWeight=[long]: 缓存的最大权重
  4. expireAfterAccess=[duration]: 最后一次写入或访问后经过固定时间过期
  5. expireAfterWrite=[duration]: 最后一次写入后经过固定时间过期
  6. refreshAfterWrite=[duration]: 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
  7. weakKeys: 打开key的弱引用
  8. weakValues:打开value的弱引用
  9. softValues:打开value的软引用
  10. recordStats:开发统计功能

注意:

  1. expireAfterWrite和expireAfterAccess同事存在时,以expireAfterWrite为准。
  2. maximumSize和maximumWeight不可以同时使用
  3. weakValues和softValues不可以同时使用

示例代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
 * @author yuhao.wang
 */
@Service
public class PersonServiceImpl implements PersonService {
  private static final Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class);
 
  @Autowired
  PersonRepository personRepository;
 
  @Override
  @CachePut(value = "people", key = "#person.id")
  public Person save(Person person) {
    Person p = personRepository.save(person);
    logger.info("为id、key为:" + p.getId() + "数据做了缓存");
    return p;
  }
 
  @Override
  @CacheEvict(value = "people")//2
  public void remove(Long id) {
    logger.info("删除了id、key为" + id + "的数据缓存");
    //这里不做实际删除操作
  }
 
  /**
   * Cacheable
   * value:缓存key的前缀。
   * key:缓存key的后缀。
   * sync:设置如果缓存过期是不是只放一个请求去请求数据库,其他请求阻塞,默认是false。
   */
  @Override
  @Cacheable(value = "people", key = "#person.id", sync = true)
  public Person findOne(Person person, String a, String[] b, List<Long> c) {
    Person p = personRepository.findOne(person.getId());
    logger.info("为id、key为:" + p.getId() + "数据做了缓存");
    return p;
  }
 
  @Override
  @Cacheable(value = "people1")//3
  public Person findOne1() {
    Person p = personRepository.findOne(2L);
    logger.info("为id、key为:" + p.getId() + "数据做了缓存");
    return p;
  }
 
  @Override
  @Cacheable(value = "people2")//3
  public Person findOne2(Person person) {
    Person p = personRepository.findOne(person.getId());
    logger.info("为id、key为:" + p.getId() + "数据做了缓存");
    return p;
  }
}

源码:https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/c72fb0c787fc

延伸 · 阅读

精彩推荐