How to clear ehcache without server restart

2019-05-02 06:12发布

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

2条回答
劫难
2楼-- · 2019-05-02 06:16

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.

查看更多
淡お忘
3楼-- · 2019-05-02 06:27

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!

查看更多
登录 后发表回答