是否可以在 Spring Boot 中使用咖啡因为每个缓存设置不同的规范? [英] Is it possible to set a different specification per cache using caffeine in spring boot?

查看:36
本文介绍了是否可以在 Spring Boot 中使用咖啡因为每个缓存设置不同的规范?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的冲刺启动应用程序,在应用程序 Configuration 类上使用 spring boot 1.5.11.RELEASE@EnableCaching.>

pom.xml

I have a simple sprint boot application using spring boot 1.5.11.RELEASE with @EnableCaching on the Application Configuration class.

 <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>

application.properties

spring.cache.type=caffeine
spring.cache.cache-names=cache-a,cache-b
spring.cache.caffeine.spec=maximumSize=100, expireAfterWrite=1d

问题

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

Question

My question is simple, how can one specify a different size/expiration per cache. E.g. perhaps it's acceptable for cache-a to be valid for 1 day. But cache-b might be ok for 1 week. The specification on a caffeine cache appears to be global to the CacheManager rather than Cache. Am I missing something? Perhaps there is a more suitable provider for my use case?

推荐答案

这是你唯一的机会:

@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.

Just expose your custom caches as beans. They are automatically added to the CaffeineCacheManager.

这篇关于是否可以在 Spring Boot 中使用咖啡因为每个缓存设置不同的规范?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆