为什么我的实体不会从我的二级缓存中被逐出?

Dav*_*ave 10 spring hibernate ehcache second-level-cache evict

我正在使用Hibernate 4.3.11.Final和Spring 3.2.11.RELEASE.我很困惑为什么我的缓存驱逐不起作用.我在DAO中设置了这个...

@Override
@Caching(evict = { @CacheEvict("main") })
public Organization save(Organization organization)
{
    return (Organization) super.save(organization);
}

@Override
@Cacheable(value = "main")
public Organization findById(String id)
{
    return super.find(id);
}
Run Code Online (Sandbox Code Playgroud)

这是我的Spring配置......

<cache:annotation-driven key-generator="cacheKeyGenerator" />

<bean id="cacheKeyGenerator" class="org.mainco.subco.myproject.util.CacheKeyGenerator" />

<bean id="cacheManager"
    class="org.springframework.cache.ehcache.EhCacheCacheManager"
    p:cacheManager-ref="ehcache"/>

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
    p:configLocation="classpath:ehcache.xml"
    p:shared="true" />

<util:map id="jpaPropertyMap">
    <entry key="hibernate.show_sql" value="true" />
    <entry key="hibernate.dialect" value="org.mainco.subco.myproject.jpa.subcoMysql5Dialect" />
    <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />
    <entry key="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" />
    <entry key="hibernate.cache.use_second_level_cache" value="true" />
    <entry key="hibernate.cache.use_query_cache" value="false" />
    <entry key="hibernate.generate_statistics" value="true" />
    <entry key="javax.persistence.sharedCache.mode" value="ENABLE_SELECTIVE" />
</util:map>

<bean id="sharedEntityManager"
    class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
Run Code Online (Sandbox Code Playgroud)

然而在下面的测试中,我的实体没有被从缓存中逐出,我知道因为"命中数#3:"的行打印出"3",而"命中数#2:"的行打印出"2" ".

private net.sf.ehcache.Cache m_cache

@Autowired 
private net.sf.ehcache.CacheManager ehCacheManager;

@Before
public void setup()
{
    m_cache = ehCacheManager.getCache("main");
    m_transactionTemplate = new TransactionTemplate(m_transactionManager);
}   // setup

...
@Test
public void testCacheEviction()
{
    final String orgId = m_testProps.getProperty("test.org.id");

    // Load the entity into the second-level cache
    m_transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {            
        m_orgSvc.findById(orgId);
        return null;
    });

    final long hitCount = m_cache.getStatistics().getCacheHits();
    System.out.println("hit count #1:" + hitCount);
    m_transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {            
        final Organization org = m_orgSvc.findById(orgId);
        System.out.println("hit count:" + m_cache.getStatistics().getCacheHits());
        org.setName("newName");
        m_orgSvc.save(org);
        return null;
    });

    // Reload the entity.  This should not incur a hit on the cache.
    m_transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {
        System.out.println("hit count #2:" + m_cache.getStatistics().getCacheHits());
        final Organization newOrg = m_orgSvc.findById(orgId);
        System.out.println("hit count #3:" + m_cache.getStatistics().getCacheHits());
        return null;
    });
Run Code Online (Sandbox Code Playgroud)

允许我从二级缓存中逐出实体的正确配置是什么?

编辑:我在应用程序上下文中引用的CacheKeyGenerator类定义如下

public class CacheKeyGenerator implements KeyGenerator 
{

    @Override
    public Object generate(final Object target, final Method method, 
      final Object... params) {

        final List<Object> key = new ArrayList<Object>();
        key.add(method.getDeclaringClass().getName());
        key.add(method.getName());

        for (final Object o : params) {
            key.add(o);
        }
        return key;
    }  
}
Run Code Online (Sandbox Code Playgroud)

因此,我不必为每个@Cacheable注释定义一个"键",我更喜欢(更少的代码).但是,我不知道这是如何适用于CacheEviction的.我认为@CacheEvict注释将使用相同的密钥生成方案.

man*_*ish 3

您缺少 和 的缓存@Cacheable@CacheEvict。因此,这两个操作使用不同的缓存键,因此该实体不会被驱逐。

来自 JavaDocs @Cacheable.key

用于动态计算密钥的 Spring 表达式语言 (SpEL) 表达式。默认值为"",这意味着所有方法参数都被视为键,除非已配置自定义 {@link #keyGenerator}。

因此,@Cacheable(value = "main") public Organization findById(String id)意味着返回的对象(类型为Organization)将与 key 一起缓存id

类似地,@Caching(evict = { @CacheEvict("main") }) public Organization save(Organization organization)意味着 的字符串表示形式organization将被视为缓存键。


解决方案是进行以下更改:

@Cacheable(value = "main", key ="#id)

@CacheEvict(value = "main", key = "#organization.id")
Run Code Online (Sandbox Code Playgroud)

这将强制两个缓存操作使用相同的密钥。