0

我正在尝试将 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

4

1 回答 1

2

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.version4.1.0.BUILD-SNAPSHOT

我已经分叉了您的项目并在此处对其进行了更新,以便它可以正常工作。检查我所做的更改将帮助您了解缺少的内容。

注意:您的 JSR-107 缓存管理器是错误的。您应该创建一个javax.cache.CacheManager,一旦拥有它,您应该将它包装到 Spring 的CacheManager. 请记住,您也可以在那里声明任何 CacheManager内容,它会起作用(SimpleCacheManager,,GuavaCacheManager等)。

于 2014-05-12T14:24:35.487 回答