我一直在寻找如何使用Spring Boot 2实现EhCache3的解决方案。问题是,在版本3中,他们将包更改为org.ehcache,而我发现的无xml配置示例适用于声明了net.sf.ehcache的2版本。 .config。我想使用第3版。
package com.jcg.example.ehcache_no_xml.config;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import net.sf.ehcache.Cache;
import net.sf.ehcache.config.CacheConfiguration;
@Configuration
public class EhCacheConfig {
@Bean
public EhCacheManagerFactoryBean cacheManager() {
return new EhCacheManagerFactoryBean();
}
@Bean
public EhCacheCacheManager testEhCacheManager() {
// testEhCache Configuration - create configuration of cache that previous required XML
CacheConfiguration testEhCacheConfig = new CacheConfiguration()
.eternal(false) // if true, timeouts are ignored
.timeToIdleSeconds(3) // time since last accessed before item is marked for removal
.timeToLiveSeconds(5) // time since inserted before item is marked for removal
.maxEntriesLocalHeap(10) // total items that can be stored in cache
.memoryStoreEvictionPolicy("LRU") // eviction policy for when items exceed cache. LRU = Least Recently Used
.name("testCache");
Cache testCache = new Cache(testEhCacheConfig);
cacheManager().getObject().addCache(testCache);
return new EhCacheCacheManager(cacheManager().getObject());
}
}
有什么解决方案可以使用spring按需创建ehCache配置?
好的,我将在不久前解决此问题的同时发布答案。我正在使用Spring Boot和下一个依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
我的缓存配置:
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public JCacheCacheManager jCacheCacheManager() {
return new JCacheCacheManager(cacheManager());
}
@Bean(value = "cacheManager")
public CacheManager cacheManager() {
CachingProvider provider = Caching.getCachingProvider();
CacheManager cacheManager = provider.getCacheManager();
List<String> cacheNames = Arrays.asList("myCacheName");
cacheNames.forEach(cn -> cacheManager.createCache(cn, config()));
return cacheManager;
}
private MutableConfiguration<SimpleKey, SiteIdSet> config() {
return new MutableConfiguration<SimpleKey, SiteIdSet>()
.setTypes(SimpleKey.class, ClassWhichShouldBeCached.class)
.setStoreByValue(false);
}
}
在开始期间,有一个方法可以检索一些值,然后将其缓存:
@Slf4j
@Service
@DependsOn("cacheManager")
public class MyServiceImpl implements MyService {
ommited ...
@Override
@Cacheable(cacheNames = "myCacheName")
public Set<Integer> getSmth() {
return callDb();
}
@Override
@CachePut(cacheNames = "myCacheName")
public Set<Integer> getSmth() {
return callDb();
}
}
我不会描述此方法的作用,但是它们可与定义的缓存一起使用,并在需要时填充和更新它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句