springBoot集成caffeine,自定义缓存配置 CacheManager
    		       		warning:
    		            这篇文章距离上次修改已过419天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,你可以通过以下步骤来集成Caffeine作为缓存,并自定义缓存配置:
- 添加Caffeine和Spring Boot Cache依赖到你的pom.xml或build.gradle文件中。
Maven的pom.xml示例依赖:
<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>- 在Spring Boot的配置类中,配置Caffeine的CacheManager。
Java配置示例:
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import java.time.duration.Duration;
 
@Configuration
@EnableCaching
public class CachingConfig {
 
    @Bean
    public CacheManager cacheManager() {
        return new CaffeineCacheManager(
            Caffeine.newBuilder()
                .expireAfterWrite(Duration.ofMinutes(10)) // 设置缓存有效期10分钟
                .maximumSize(1000) // 设置缓存最大条目数
                .build()
        );
    }
}在上述配置中,我们创建了一个CaffeineCacheManager实例,并通过Caffeine.newBuilder()定制了缓存的行为,例如设置缓存失效时间和最大容量。
- 使用@Cacheable,@CachePut,@CacheEvict等注解在你的服务方法上,启用缓存功能。
例如:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
 
@Service
public class SomeService {
 
    @Cacheable(value = "itemCache", key = "#id")
    public Item findItemById(Long id) {
        // 实现查找逻辑
    }
}在上述服务类中,findItemById方法被标记为@Cacheable,这意味着Spring将缓存该方法的返回值,并在后续调用相同参数时重用缓存的结果。
确保你的Spring Boot版本和Caffeine库版本兼容,并且已经正确地添加了必要的依赖。
评论已关闭