簡體   English   中英

Spring緩存不能與EHCache + JCache一起使用

[英]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 ,它可以工作( SimpleCacheManagerGuavaCacheManager等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM