cutom ehcache evict policy with spring

1.3k views Asked by At

If we want to custom evict policy besides LRU LFU FIFO, the way docs recommanded is to implement interface Policy then set MemoryStoreEvictionPolicy like:

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

but if I used spring, use @cacheable and xml files like

<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>

how can I inject my own policy in spring way?

thank you all

1

There are 1 answers

0
Will Keeling On BEST ANSWER

You may be best to implement your own class that sets the eviction policy on the cache when Spring initializes.

For example:

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;
    }
}

And then in your Spring config:

<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>