经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
Spring Cache + Caffeine的整合与使用
来源:cnblogs  作者:Scotyzh  时间:2023/12/15 8:46:55  对本文有异议

前言

对于一些项目里需要对数据库里的某些数据一直重复请求的,且这些数据基本是固定的,在这种情况下,可以借助简单使用本地缓存来缓存这些数据。这些介绍一下Spring Cache和Caffeine的使用。

引入依赖和CacheConfig

在pom文件里面引入下面的依赖:

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

在启动类上加上@EnableCaching的注解

  1. @EnableCaching
  2. public class SpringBootApplication{
  3. }

新建一个CacheConfig类

  1. @Configuration
  2. public class CacheConfig {
  3. /********************************
  4. * @function : 生成缓存管理器
  5. * @parameter : []
  6. * @return : org.springframework.cache.CacheManager
  7. * @date : 2023/12/13 14:46
  8. ********************************/
  9. @Primary
  10. @Bean("customCacheManager")
  11. public CacheManager customCacheManager() {
  12. SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
  13. List<Cache> cacheList = new ArrayList<>();
  14. cacheList.add(customCache());
  15. simpleCacheManager.setCaches(cacheList);
  16. return simpleCacheManager;
  17. }
  18. /********************************
  19. * @function : 生成自定义缓存容器
  20. * @parameter : []
  21. * @return : org.springframework.cache.Cache
  22. * @date : 2023/12/13 14:46
  23. ********************************/
  24. public Cache customCache() {
  25. return new CaffeineCache("customCache", Caffeine.newBuilder()
  26. .build(), true);
  27. }
  28. }

这里customCache()方法我并没有设置相关过期时间和最大值,不设置会导致没有默认过期时间和最大值。如果需要设置可以参考下面的写法

  1. public Cache customCache() {
  2. return new CaffeineCache("customCache", Caffeine.newBuilder()
  3. .maximumSize(100)
  4. .initialCapacity(100)
  5. .expireAfterWrite(10, TimeUnit.MINUTES)
  6. .recordStats()
  7. .build(),
  8. true);
  9. }

CaffeineCache参数的讲解

  1. "customCache": 这是缓存的名称。在应用程序中,你可以通过这个名称来获取对应的缓存实例。
  2. Caffeine.newBuilder(): 这是创建Caffeine缓存实例的起始点。newBuilder()返回一个Caffeine构建器对象,用于配置和定制缓存的各种属性。
  3. .maximumSize(100): 这是设置缓存的最大容量,即缓存可以容纳的最大条目数。在这个例子中,缓存的最大容量被设置为100。
  4. .initialCapacity(100): 这是设置缓存的初始容量,即在缓存初始化时分配的内部数据结构的初始大小。在这个例子中,初始容量被设置为100。
  5. .expireAfterWrite(10, TimeUnit.MINUTES): 这是设置缓存项在被写入后的过期时间。在这个例子中,缓存项将在被写入后的10分钟内过期。
  6. .recordStats(): 这是启用缓存统计信息的选项。启用后,你可以从缓存实例中获取有关缓存使用情况的统计信息,例如命中率、加载次数等。

使用中,对过期策略的使用会比较重要,对于过期的策略有:

  1. 写入后过期 (expireAfterWrite): 缓存项被写入后的一段时间内过期。可以通过以下方式配置:

    1. Caffeine.newBuilder()
    2. .expireAfterWrite(10, TimeUnit.MINUTES)
    3. .build();

    在上述示例中,缓存项将在被写入后的10分钟内过期。

  2. 访问后过期 (expireAfterAccess): 缓存项在一段时间内没有被访问后过期。可以通过以下方式配置:

    1. Caffeine.newBuilder()
    2. .expireAfterAccess(15, TimeUnit.MINUTES)
    3. .build();

    在上述示例中,缓存项将在最后一次访问后的15分钟内过期。

  3. 定时过期 (expireAfter): 缓存项在指定的固定时间内过期,不考虑写入或访问。可以通过以下方式配置:

    1. Caffeine.newBuilder()
    2. .expireAfter(1, TimeUnit.HOURS)
    3. .build();

    在上述示例中,缓存项将在创建后的1小时内过期。

这些过期定时策略可以根据具体的使用场景和需求进行组合或选择。

上面不同写法将会导致生成不同的localcache实现类,可以在build方法中看到:

image-20231213211003206

进入isBounded()方法:

image-20231213211041692

如果使用缓存会调用localcache的get方法,最后进入computeIfAbsent()方法,对比上面两个实现类的实现,先是BoundedLocalCache:

image-20231213211342736

UnboundedLocalCache:

image-20231213211443944

下面这个并不会去检查是否过期。

使用示范

在MVC的使用,可以将缓存的注解标识于service层:

  1. @Service
  2. @Slf4j
  3. @CacheConfig(cacheNames = "customCache", cacheManager = "customCacheManager")
  4. public class CalDataInitServiceImpl implements ICalDataInitService {
  5. @Cacheable(key = "#root.methodName + #sendCardName")
  6. public int getSlotCount(String sendCardName) {
  7. ..方法体
  8. return calCard.getSlotCount();
  9. }
  10. ...
  11. @CachePut(key = "#param")
  12. public String updateCache(String param) {
  13. // 对数据库更新某个值
  14. return updatedValue;
  15. }
  16. @CacheEvict(key = "#param")
  17. public void evictCache(String param) {
  18. // 对数据库删除某个值
  19. }
  20. }

使用到的注解解析:

@CacheConfig(cacheNames = "customCache", cacheManager = "customCacheManager") 标注在类上,cacheNames表示当前使用的缓存名字,在创建缓存的时候有指定,第二个cacheManager是创建cacheManager管理器时指定的Bean名称,这里是 @Bean("customCacheManager")。

@Cacheable 是Spring框架中用于声明缓存规则的注解之一。它通常用于标记在方法上,以指示Spring在执行方法前先检查缓存,如果缓存中已有数据,则直接返回缓存中的数据,而不执行方法体。如果缓存中没有数据,则执行方法体,并将方法的返回值存入缓存。

以下是 以@Cacheable 注解为例的主要参数介绍和使用方式:

  1. value(或 cacheNames): 指定缓存的名称,可以指定一个或多个缓存。如果指定多个缓存,Spring会依次检查缓存,直到找到第一个有数据的缓存或全部检查完毕。示例:

    1. @Cacheable(value = "myCache")
    2. public String getCachedData() {
    3. // 方法体
    4. }
  2. key 指定缓存项的键。默认情况下,Spring会使用方法的参数作为键,但你也可以通过 key 属性指定自定义的缓存键。示例:

    1. @Cacheable(value = "myCache", key = "#param")
    2. public String getCachedData(String param) {
    3. // 方法体
    4. }
  3. condition 指定条件表达式,只有当条件满足时才会缓存。示例:

    1. @Cacheable(value = "myCache", condition = "#result != null")
    2. public String getCachedData() {
    3. // 方法体
    4. }
  4. unless 指定一个条件表达式,当条件为 true 时,不会将结果放入缓存。示例:

    1. @Cacheable(value = "myCache", unless = "#result == null")
    2. public String getCachedData() {
    3. // 方法体
    4. }
  5. keyGenerator 指定自定义的缓存键生成器。这个属性允许你提供一个实现了 org.springframework.cache.interceptor.KeyGenerator 接口的类,用于生成缓存键。示例:

    1. @Cacheable(value = "myCache", keyGenerator = "customKeyGenerator")
    2. public String getCachedData() {
    3. // 方法体
    4. }
  6. sync 是否启用同步模式。如果设置为 true,可以解决并发查的问题,Spring会在调用方法时锁定缓存,防止多个线程同时访问数据库。默认为 false。示例:

    1. @Cacheable(value = "myCache", sync = true)
    2. public String getCachedData() {
    3. // 方法体
    4. }

这些是 @Cacheable 注解的一些常用参数。可以根据实际需要选择合适的参数来定义缓存规则。

在Spring中,除了 @Cacheable,另外一些注解及其简要介绍:

  1. @CacheEvict 用于从缓存中移除数据。通常用于在方法执行后清空指定缓存。示例:

    1. @CacheEvict(value = "myCache", key = "#param")
    2. public void evictCache(String param) {
    3. // 方法体
    4. }
  2. @CachePut 用于将方法的返回值更新到缓存中,常用于更新缓存而不影响方法的执行。示例:

    1. @CachePut(value = "myCache", key = "#param")
    2. public String updateCache(String param) {
    3. // 方法体
    4. return updatedValue;
    5. }
  3. @Caching 用于将多个缓存相关的注解组合在一起,实现复杂的缓存操作。示例:

    1. @Caching(
    2. evict = {@CacheEvict(value = "cache1", key = "#param1")},
    3. put = {@CachePut(value = "cache2", key = "#param2")}
    4. )
    5. public String complexCacheOperation(String param1, String param2) {
    6. // 方法体
    7. }
  4. @CacheConfig 用于在类级别配置缓存的一些公共属性,避免在每个方法上都重复指定相同的缓存名称等信息。示例:

    1. @CacheConfig(cacheNames = "commonCache")
    2. public class MyService {
    3. @Cacheable
    4. public String getCachedData(String param) {
    5. // 方法体
    6. }
    7. }

这些注解可以单独使用,也可以结合使用,以满足不同的缓存需求。

清空缓存的方法

清空所有缓存,可以不指定 valuekey,如下所示:

  1. @CacheEvict(allEntries = true)
  2. public void evictAllCaches() {
  3. // 方法体
  4. }

在这个例子中,allEntries = true 表示清空所有缓存。

如果你想根据某个条件来判断是否清空缓存,可以使用 condition 属性,例如:

  1. @CacheEvict(value = "myCache", key = "#param", condition = "#param != 'noEviction'")
  2. public void evictCacheConditionally(String param) {
  3. // 方法体
  4. }

在上述例子中,只有当 param 不等于 'noEviction' 时才会执行缓存清空操作。

除了 @CacheEvict,在一些特定场景下,@CachePut 也可以被用来“清空”缓存,因为它将方法的返回值放入缓存,如果返回值为 null,相当于移除缓存项。这种方式通常在更新操作时使用。

注意事项

如下图代码所示,如果在updateCache方法又调用了同个类里面的getSlotCount()方法,是不会使用到缓存的,这是因为缓存的实现是通过AOP实现,在同个类里面调用方法,实际是通过this来调,不会调用到代理对象,因此相当于@Cacheable注解在这种情况是不生效的。

  1. @Service
  2. @Slf4j
  3. @CacheConfig(cacheNames = "customCache", cacheManager = "customCacheManager")
  4. public class CalDataInitServiceImpl implements ICalDataInitService {
  5. @Cacheable(key = "#root.methodName + #sendCardName")
  6. public int getSlotCount(String sendCardName) {
  7. ..方法体
  8. return calCard.getSlotCount();
  9. }
  10. ...
  11. @CachePut(key = "#param")
  12. public String updateCache(String param) {
  13. getSlotCount("xx");
  14. // 对数据库更新某个值
  15. return updatedValue;
  16. }
  17. }

原文链接:https://www.cnblogs.com/scottyzh/p/17900921.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号