定制ehcache用spring驱逐政策

时间:2013-12-08 02:49:57

标签: spring ehcache evict

如果我们想要除LRU LFU FIFO之外的自定义驱逐策略,docs推荐的方式是实现接口Policy然后设置MemoryStoreEvictionPolicy如:

manager = new CacheManager(EHCACHE_CONFIG_LOCATION);
cache = manager.getCache(CACHE_NAME);
cache.setMemoryStoreEvictionPolicy(new MyPolicy());

但如果我使用spring,请使用@cacheable和xml文件,如

<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml" ></property>
</bean>


<!-- cacheManager -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="cacheManagerFactory" />
</bean>

如何以春季方式注入自己的政策?

谢谢大家

1 个答案:

答案 0 :(得分:3)

最好在Spring初始化时实现自己的类,在缓存上设置驱逐策略。

例如:

public class MyEvictionPolicySetter implements InitializingBean {

    public static final String CACHE_NAME = "my_cache";

    private CacheManager manager;
    private Policy evictionPolicy;

    @Override
    public void afterPropertiesSet() {
        Cache cache = manager.getCache(CACHE_NAME);
        cache.setMemoryStoreEvictionPolicy(evictionPolicy);
    }

    public void setCacheManager(CacheManager manager) {
        this.manager = manager;
    }

    public void setEvictionPolicy(Policy evictionPolicy) {
        this.evictionPolicy = evictionPolicy;
    }
}

然后在你的Spring配置中:

<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml" ></property>
</bean>

<!-- Specify your eviction policy as a Spring bean -->
<bean id="evictionPolicy" class="MyPolicy"/>

<!-- This will set the eviction policy when Spring starts up -->
<bean id="evictionPolicySetter" class="EvictionPolicySetter">
    <property name="cacheManager" ref="cacheManagerFactory"/>
    <property name="evictionPolicy" ref="evictionPolicy"/>
</bean>