Caffeine Cache缓存

发布时间 2023-12-01 19:08:53作者: 鲤斌

SpringBoot 集成 Caffeine

Caffeine 和 Spring Cache 依赖,使用注解方法实现缓存

依赖

<!--提供 Spring Boot 中的缓存支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

<!--        Caffeine Cache 的具体实现-->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>

配置缓存

1,Config
package com.james.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {
    
    //通过 Caffeine.newBuilder() 构建一个 Caffeine 实例,并设置最大大小为 500 个条目,过期时间为 600 秒
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .initialCapacity(1000) //// 初始的缓存空间大小
                .maximumSize(500) // // 缓存的最大条数
                .expireAfterAccess(60, TimeUnit.SECONDS)); // 设置最后一次写入或访问后经过固定时间过期
        return cacheManager;
    }
}
2,yml
spring:
  #通过 spec 属性指定了缓存的一些属性,比如最大大小为 500 个条目,并设置了过期时间为 600 秒  2选一
  cache:
    caffeine:
      spec: maximumSize=500,expireAfterAccess=600s

 注解集成

@Cacheable:将方法的返回值缓存起来,并在后续对同样的方法进行调用时,直接返回缓存中的结果,而不会执行方法的实际逻辑;

//那么方法的返回值会被缓存在名为 “myCache” 的缓存中,而不会根据方法的参数进行细分。
//这种方式适用于方法的返回值在不同参数下是相同的,或者不关心具体的参数对应的缓存
  @Cacheable(cacheNames = "myCache")
    public String getCachedData(String key) {
      // 从数据库或其他数据源获取数据
      return data;
  }
 //则可以根据方法的参数进行细分缓存。每个不同的 Id 参数会对应一个不同的缓存键,从而实现了更精确的缓存控制。
//这种方式适用于每个参数对应的结果可能不同,或者需要根据不同的参数缓存不同的结果。
  @Cacheable(value = "listTypeBook", key = "#Id")
    public List<BookEntity> listTypeBook(Integer Id) {
        List<BookEntity> bookEntities = bookMapper.listTypeBook(Id);
        return bookEntities;
    }

@CachePut:用于更新或添加缓存的值。无论缓存是否已存在,该方法都会执行,并将结果放入缓存中;

//方法 updateCache() 将通过 key 更新名为 “myCache” 的缓存的值
//无论是添加缓存还是更新缓存,都会执行方法体内的逻辑,并将结果更新到缓存中
@CachePut(cacheNames = "myCache", key = "#key")
public String updateCache(String key, String value) {
    // 更新数据
    return updatedData;
}

@CacheEvict:用于从缓存中删除数据。使用该注解会删除指定缓存名称中的一个或多个缓存条目;

//方法 evictCache() 将从名为 “myCache” 的缓存中删除具有指定 key 的缓存条目
@CacheEvict(cacheNames = "myCache", key = "#key")
public void evictCache(String key) {
    // 删除数据
}

只引入 Caffeine 依赖,然后使用 Caffeine 方法实现缓存

<!--        Caffeine Cache 的具体实现-->
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
config
@Configuration
public class CacheConfig {
    @Bean
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .build();
    }
    @Bean
    public Cache<Integer, List<BookEntity>> caffeineCache3() {
        return Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .build();
    }
}
代码
    @Resource
     Cache<Integer, List<BookEntity>> caffeineCache1;
    @Resource
    Cache<String, Object> caffeineCache;

 //
    @Override
    public List<BookEntity> listTypeBook1(Integer id) {
        // 从缓存中获取集合对象
        List<BookEntity> cachedList = caffeineCache1.getIfPresent(id);
        if (cachedList != null) {
            return cachedList;
        }

        // 如果缓存中不存在,则从数据库中获取集合对象
        List<BookEntity> bookEntities = bookMapper.listTypeBook(id);

        // 将集合对象保存到缓存中
        caffeineCache1.put(id, bookEntities);

        return bookEntities;
    }

 // 添加缓存项
caffeineCache1.put(1, books);

// 修改缓存项
 caffeineCache1.put(1, updatedBooks);

 // 删除缓存项
caffeineCache1.invalidate(1);