spring-boot - 是否可以在 Spring Boot 中使用咖啡因为每个缓存设置不同的规范?

标签 spring-boot spring-cache caffeine

我有一个使用 spring boot 的简单冲刺启动应用程序 1.5.11.RELEASE@EnableCaching关于申请 Configuration类(class)。

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.cache.type=caffeine
spring.cache.cache-names=cache-a,cache-b
spring.cache.caffeine.spec=maximumSize=100, expireAfterWrite=1d



我的问题很简单,如何为每个缓存指定不同的大小/到期时间。例如。或许 cache-a 可以接受对 1 day 有效.但是cache-b可能没问题 1 week .关于咖啡因缓存的规范似乎对 CacheManager 来说是全局的。而不是 Cache .我错过了什么吗?也许有更适合我的用例的提供程序?

最佳答案

这是你唯一的机会:

@Bean
public CaffeineCache cacheA() {
    return new CaffeineCache("CACHE_A",
            Caffeine.newBuilder()
                    .expireAfterAccess(1, TimeUnit.DAYS)
                    .build());
}

@Bean
public CaffeineCache cacheB() {
    return new CaffeineCache("CACHE_B",
            Caffeine.newBuilder()
                    .expireAfterWrite(7, TimeUnit.DAYS)
                    .recordStats()
                    .build());
}

只需将您的自定义缓存公开为 bean。它们会自动添加到 CaffeineCacheManager .

关于spring-boot - 是否可以在 Spring Boot 中使用咖啡因为每个缓存设置不同的规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885064/

相关文章:

java - Spring Boot 禁止属性值

spring-boot - 使用 Spring Actuator 时无法排除/info 和/health/{*path}

多模块 Spring Boot 项目中的 Gradle 依赖插件

java - 为什么我在使用 Spring Cache 的服务中出现缓存未命中的情况

java-8 - 如何在 RxJava 中缓存项目并避免缓存踩踏?

java - 自定义错误页面未捕获 tomcat 中引发的异常

spring - @Async 和 @Cacheable 缓存非空响应

java - 如何在 Spring 启动时加载@Cache?

java - Spring Cache - @CachePut 和 @CacheEvict 之间的真正区别