java - 咖啡因 Springboot 集成

标签 java spring-boot caching caffeine

我们使用caffeine来替换当前springboot中默认的ConcurrentHashMap缓存。我们使用 @Cacheable(cacheNames = { "..."}) 注释动态创建缓存。

我正在尝试设置 recordStats 属性,因为我们正在使用 springboot 执行器包来监视应用程序的各个方面。

我尝试在application.properties中设置spring.cache.caffeine.spec=expireAfterAccess=3600s,recordStats,但不起作用。

@Configure 类中设置它也不起作用:

@Configuration
public class CacheConfig {

  @Bean
  public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager();
    cacheManager.setCacheSpecification("expireAfterAccess=3600s,recordStats");
    return cacheManager;
  }
}

缓存统计信息不会出现在 /actuator/cache/{caches} 端点或我们的 springboot-admin 服务器中。

根据当前的 api 文档,我发现:

The string syntax is a series of comma-separated keys or key-value pairs, each corresponding to a Caffeine builder method.

initialCapacity=[integer]: sets Caffeine.initialCapacity.

...

recordStats: sets Caffeine.recordStats(). 

Durations are represented by an integer, followed by one of "d", "h", "m", or "s", representing days, hours, minutes, or seconds respectively. There is currently no syntax to request expiration in milliseconds, microseconds, or nanoseconds.

Whitespace before and after commas and equal signs is ignored. Keys may not be repeated; it is also illegal to use the following pairs of keys in a single value:

maximumSize and maximumWeight
weakValues and softValues 

相关点:

CaffeineSpec does not support configuring Caffeine methods with non-value parameters. These must be configured in code.

我的任务没有可能完成吗?

谢谢

最佳答案

您可以手动为缓存定义bean,例如

@Bean
public Cache recorded() {
    return new CaffeineCache("recorded", Caffeine.newBuilder()
            .recordStats()
            .build());
}

Spring Boot 将拾取此 bean,您将能够在代码中使用 @Cacheable("recorded")(注意匹配的缓存名称)。

此外,我的 Caffeine 和 Spring Boot 宠物项目也可能对您有用: https://github.com/stepio/coffee-boots

这个确切的 recordStats() 设置功能并未在那里进行测试,但错误报告和 PR 总是值得赞赏的。

PS:相关问题: Dynamically toggling recording stats on Caffeine Cache

干杯!

关于java - 咖啡因 Springboot 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59980554/

相关文章:

php - Memcache city lookup table 与否

java - 动态添加textview到CardView

java - 如何使用加速度计值显示数字

java - VS代码无法读取java文件

java - 保存后 Spring Data 存储库不加载关系

ASP.Net 使用状态服务器和缓存增加 MaxProcesses(网络花园)

java - 在数字列表上使用 RegisterCustomerEditor 进行 Spring 数字格式化

java - 删除 CN 中带有 0x0A 的 LDAP 记录 (Java)

spring - java.io.IOException : Broken pipe bringing down the embedded tomcat 8 app

spring-boot - 无法创建 tempDir,java.io.tmpdir 设置为 C :\Windows\