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