2013-12-08 48 views
2

如果我们想要定制驱逐政策除了LRU LFU FIFO,文件建议报告的方式是实现接口政策再设置MemoryStoreEvictionPolicy像:对自定义的Ehcache驱逐政策,春天

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

,但如果我用弹簧,使用@可缓存和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> 

我怎样才能在春季注入我自己的策略?

谢谢大家

回答

3

你可能是最好地实现自己的类,设置在高速缓存中的驱逐策略时,春初始化。

例如:

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

感谢这真的合理 – cedrics