咖啡因 Springboot 集成

Caffeine Springboot integration

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

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

我试图在application.properties中设置spring.cache.caffeine.spec=expireAfterAccess=3600s,recordStats,但是没有用。

将其设置为 @Configure class 也不起作用:

@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());
}

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

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

这个确切的 recordStats() 设置功能没有在那里测试,但是错误报告和 PR 总是很受欢迎。

P.S.: 相关问题:

干杯!

我成功了。这是代码:

@Configuration
public class CacheConfig {

  @Bean
  public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager("cache1",
        "cache2", "cache3");
    cacheManager.setCacheSpecification("recordStats");
    return cacheManager;
  }
}

仍然有缺点,缓存名称必须与 @Cacheable(cachenames={"..."}) 注释中的名称相匹配