[英]Spring cache not working with EHCache+JCache
我正在尝试将jcache的ehcache实现集成到spring中。 所以我有一个这样定义的外观:
@Component(value = "sampleFacade")
@CacheDefaults(cacheName = "default")
public class SampleFacadeImpl implements SampleFacade
{
@Override
@CacheResult(cacheName = "site")
public SitePojo getSiteForUid(final String uid)
{
System.out.println("getting the site for uid: " + uid);
final SitePojo pojo = new SitePojo();
pojo.setUid(uid);
pojo.setUrl(uid);
return pojo;
}
}
和基于java的配置,如下所示:
@Configuration
@EnableCaching(mode = AdviceMode.PROXY)
@ComponentScan(basePackages = { "com.test" })
public class TestConfig implements CachingConfigurer
{
@Resource
public ApplicationContext context;
@Override
@Bean(name = { "defaultKeyGenerator", "keyGenerator" })
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
@Override
@Bean(name = { "defaultCacheManager", "cacheManager" })
public CacheManager cacheManager() {
final JCacheCacheManager cacheManager = new JCacheCacheManager();
cacheManager.setCacheManager((javax.cache.CacheManager) context.getBean("cacheManagerFactoryBean"));
return cacheManager;
}
@Bean(name = { "defaultCacheManagerFactoryBean", "cacheManagerFactoryBean" })
protected JCacheManagerFactoryBean defaultCacheManagerFactoryBean() {
return new JCacheManagerFactoryBean();
}
}
和一次调用立面10次的测试:
@Test
public void testGetSiteForUid() {
for (int i = 0; i < 10; i++) {
assertNotNull(sampleFacade.getSiteForUid("uid"));
}
}
但结果是通过该方法10次:
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
getting the site for uid: uid
你可以在这里找到一个示例项目来重现它: https : //github.com/paranoiabla/spring-cache-test
JCache支持是Spring 4.1的一个新功能。 您正在使用4.0.4但尚未获得此支持。
Spring Framework 4.1尚未发布。 您可以通过将以下内容添加到项目中来尝试快照
<repositories>
<repository>
<id>spring-snapshot</id>
<name>Springframework Snapshot Repository</name>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
并将spring.version
翻转为4.1.0.BUILD-SNAPSHOT
我已经分叉你的项目并在这里更新它,以便它可以正常工作。 检查我改变了什么会帮助你理解缺少的东西。
注意:您的JSR-107缓存管理器是错误的。 你应该创建一个javax.cache.CacheManager
,一旦你拥有它,你应该将它包装到Spring的CacheManager
。 请记住,您也可以在那里声明任何 CacheManager
,它可以工作( SimpleCacheManager
, GuavaCacheManager
等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.