java - 从 GuavaCache 迁移到 EhCache (Spring Boot)
问题描述
我正在尝试更改以下方法以使用 EhCache 缓存而不是 Guava 缓存,因为从 Spring 5.0 中删除了 Guava 缓存。似乎没有任何关于如何简单地实例化 EhCacheCache 对象并将其传递给 SimpleCacheManager 的在线文档。我如何实现这一目标?
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
GuavaCache a =
new GuavaCache("a", CacheBuilder.newBuilder().maximumSize(10000)
.expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());
GuavaCache b =
new GuavaCache("b", CacheBuilder.newBuilder().maximumSize(100)
.expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());
GuavaCache c =
new GuavaCache("c", CacheBuilder.newBuilder().maximumSize(100)
.expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());
GuavaCache d =
new GuavaCache("d", CacheBuilder.newBuilder().maximumSize(20)
.expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());
GuavaCache e =
new GuavaCache("e", CacheBuilder.newBuilder().maximumSize(100)
.expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());
GuavaCache f =
new GuavaCache("f", CacheBuilder.newBuilder().maximumSize(10)
.expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());
GuavaCache g =
new GuavaCache("g", CacheBuilder.newBuilder().maximumSize(5000)
.expireAfterAccess(24, TimeUnit.HOURS).recordStats().build());
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
simpleCacheManager.setCaches(
Arrays.asList(
a,
b,
c,
d,
e,
f,
g
)
);
return simpleCacheManager;
}
}
解决方案
这不是它的工作方式。假设您将使用 Ehcache 3.x,它符合 JSR107。所以你会使用JCacheCacheManager
. 当看到类路径中的 jcache api 可用时,Spring-boot 将对其进行配置而不做任何事情。
事实上,最简单的方法通常是让它做它并使用 aJCacheManagerCustomizer
添加你想要的缓存。如下所示。
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
return cm -> {
cm.createCache("a", createConfiguration(100, Duration.ofHours(24)));
};
}
private javax.cache.configuration.Configuration<Object, Object> createConfiguration(long size, Duration tti) {
return Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
ResourcePoolsBuilder.heap(size))
.withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(tti))
.build());
}
}
推荐阅读
- reactjs - 如何在蚂蚁设计列表项上添加悬停
- javascript - Promise 构造函数和“属性 'handleEvent' 不可调用”错误
- c# - C# 并删除 SQL Server 数据库中的特定行
- php - 如何从多维数组创建 csv 文件?
- swift - 在 Mac App JSContext 中访问文件系统
- ruby-on-rails - activerecord 在单个语句中查找和更新
- mysql - 如果我只有 Tableau 服务器的超链接以及用户名和密码,我可以将数据库与 MySQL 连接吗?
- dynamics-crm - 位置 address1_city,address2_stateorprovince,address1_country,address1_county 跟踪
- git - 使用 github 存储库中的其他帐户提交
- video - ffmpeg 流循环 CPU 100%