如何定期驱逐不经常使用的缓存区域?

时间:2014-12-09 10:54:26

标签: java hibernate ehcache

根据这个 Ehcache_Configuration_Guide.pdf

  

配置如何影响元素刷新和驱逐


  以下示例显示了具有特定到期时间的缓存:
      <cache name="myCache"
       eternal="false" timeToIdleSeconds="3600"
       timeToLiveSeconds="0" memoryStoreEvictionPolicy="LFU">
      </cache>
  请注意以下有关myCache配置的信息:
  如果客户端访问myCache中已空闲超过一小时timeToIdleSeconds的条目,则该元素被逐出。
  如果条目过期但未被访问,并且没有资源约束强制驱逐,则过期条目保持不变,直到定期逐出器将其删除。

我没有找到如何定期配置驱逐的任何例子,

可配置吗? 或者必须对hibernate进行硬编码?

根据此页ExpiryTaskExtension.java ehCache中没有默认的时间驱逐计划

1 个答案:

答案 0 :(得分:0)

import java.util.Timer;
import java.util.TimerTask;
import net.sf.ehcache.CacheManager;

public class EhCacheExpiryTask {
    class ExpiryTask extends TimerTask{
        @Override
        public void run() {
            for (CacheManager manager : CacheManager.ALL_CACHE_MANAGERS) {
                for (String name : manager.getCacheNames()) {
                    //manager.getCache(name).getCacheConfiguration().setStatistics(true);
                    manager.getCache(name).evictExpiredElements();                 
                } 
            }        
        }
    }
    private Timer timer;
    private long period;
    private ExpiryTask expiryTask;
    public EhCacheExpiryTask(long period){
        this.period = period;
        this.timer = new Timer();
    } 
    public void stop(){
        timer.cancel();
    }
    public void start(){
        expiryTask = new ExpiryTask();      
        timer.schedule(expiryTask, 10000, period);
    }
}
相关问题