How to clear ehcache without server restart

南楼画角 提交于 2019-12-07 04:47:13

问题


Though I guess its highly unlikely - but is there any way to clear the ehcache without restarting the server? I need to clear the cache for some testing - I cannot change the code and cannot afford to restart server at multiple times.

PS: I am using apache-tomcat-5.5.25 Please let me know. Thanks, psvm


回答1:


Do you expose Ehcache via JMX? Then you could clear the cache using JMX operations by using a tool like e.g. jvisualvm. Look for MBeans like net.sf.ehcache.CacheManager which provide a clearAll() operation.




回答2:


Using spring+hibernate and exposing mbean:

import org.hibernate.Cache;
import org.hibernate.SessionFactory;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("CacheManagerMBean")
public class CacheManagerMBean {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CacheManagerMBean.class);

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    public void clearCache() {
        Cache cache = sessionFactory.getCache();
        if (null != cache) {
            logger.info("Clearing cache...");
            cache.evictAll();
            cache.evictAllRegions();
            logger.info("Clearing cache...Done!");
        } else {
            logger.error("No second level cache available for session-factory");
        }
    }

}

XML Config:

<bean id="jmxExporterCacheManagerMBean" class="org.springframework.jmx.export.MBeanExporter">
        <property name="beans">
            <map>
                <entry key="CacheManager:type=SecondLevelCacheManager">
                    <ref bean="CacheManagerMBean"/>
                </entry>
            </map>
        </property>
    </bean>

And then connect to the java process using jconsole and use Mbean method invocation - to clear the second level cache!



来源:https://stackoverflow.com/questions/10912087/how-to-clear-ehcache-without-server-restart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!