Remember it once, ehcache caches to disk, and then restores the process

 

The problem is: cache to the hard disk, shut down the server and then restart, the previous cached data cannot be obtained 

 

environment:

 

 

ehcache version:

                <dependency>
		    <groupId>net.sf.ehcache</groupId>
		    <artifactId>ehcache-core</artifactId>
		    <version>2.5.2</version>
		</dependency>

 

 

 

ehcache.xml:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="spring_oa" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false">
<!-- <diskStore path="java.io.tmpdir"/> Java temporary directory -->
    <diskStore path="d:\cache"/> <!-- Java temporary directory -->
	<!--
        Configure custom cache
        maxElementsInMemory: The maximum number of objects allowed to be created in the cache
        eternal: Whether the object in the cache is permanent, if so, the timeout setting will be ignored and the object never expires.
        timeToIdleSeconds: Passivation time of cached data, that is, before an element dies, (idle time)
                    The maximum time interval between two access times, which is only valid if the element is not permanently resident,
                    A value of 0 means that the element can be paused for an infinite amount of time.
        timeToLiveSeconds: The lifetime of cached data, that is, the maximum time interval from construction to death of an element,
                    This only works if the element is not permanently resident, a value of 0 means the element can be paused for an infinite amount of time.
        overflowToDisk: Whether to enable disk caching when memory is insufficient.
        memoryStoreEvictionPolicy: The elimination algorithm after the cache is full.
    -->
    <!-- My understanding is that the "default cache" is actually a template for new caches that get created, rather than being a specific named cache.  -->
	<defaultCache
       maxElementsInMemory="1000"
       eternal="false"
       timeToIdleSeconds="120"
       timeToLiveSeconds="120"
       overflowToDisk="false"/>

    <!-- Maximum date cached to disk -->
    <!-- Police -->
    <cache name="jq_maxDateCache"
           maxElementsInMemory="1"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="true"
           memoryStoreEvictionPolicy="LFU" >
                 
<!--            timeToIdleSeconds="60"	 -->
<!--            timeToLiveSeconds="0" -->
<!--            overflowToDisk="false" -->
<!--            statistics="true" -->
        <BootstrapCacheLoaderFactory class="net.sf.ehcache.store.DiskStoreBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true" />
<!-- <cacheEventListenerFactory -->
<!--             class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />   -->
<!-- This is more than the general configuration -->
<!--         <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>   -->
    </cache>
    <!-- Maximum date cached to disk -->
    <!-- Dispatch Squadron-->
    <cache name="dpzd_maxDateCache"
           maxElementsInMemory="1"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="true"
           memoryStoreEvictionPolicy="LFU" >
                 
        <BootstrapCacheLoaderFactory class="net.sf.ehcache.store.DiskStoreBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true" />

<!-- <cacheEventListenerFactory -->
<!--             class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />   -->
<!-- This is more than the general configuration -->
<!--         <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>   -->
    </cache>
    <!-- Maximum date cached to disk -->
    <!-- Dispatch Vehicles-->
    <cache name="dpcl_maxDateCache"
           maxElementsInMemory="1"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="true"
           memoryStoreEvictionPolicy="LFU" >
                 
        <BootstrapCacheLoaderFactory class="net.sf.ehcache.store.DiskStoreBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true" />
<!-- <cacheEventListenerFactory -->
<!--             class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />   -->
<!-- This is more than the general configuration -->
<!--         <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>   -->
    </cache>

   
</ehcache>

 applicationContext-cache.xml:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- The cache manager based on the Ehcache implementation provided by Spring -->
	
    <!-- If there are multiple ehcacheManagers, add p:shared="true" to the bean -->
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache/ehcache.xml"/>
    </bean>
    
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache"/>
    </bean>



</beans>

 CacheUtils:

 

 

package jiangdu.fire.util.wj;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.util.CollectionUtils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

/**
 * Cache tool class
 * @author wj
 * @date 2016-12-31
 */

public class CacheUtils {
	
	private static Logger logger = LoggerFactory.getLogger(CacheUtils.class);
	private static EhCacheCacheManager cacheManager = SpringContextHolder.getBean("ehcacheManager");
	
	
	 public static Object get(String cacheName, Object key) {  
	        Cache cache = getCache(cacheName);  
	        if (cache != null) {  
	        	logger.debug("------缓存["+cacheName+"] size:"+cache.getSize());
//	        	 System.out.println("------缓存["+cacheName+"] size:"+cache.getSize());  
	        	 
	        	 List<String> keys = cache.getKeys();
	        	 if(!CollectionUtils.isEmpty(keys)){
	        		 for( String key1 : keys){
	        			 logger.debug("------缓存["+cacheName+"] key:"+key1+",value:"+cache.get(key1).getObjectValue());
//		        		 System.out.println("------缓存["+cacheName+"] key:"+key1+",value:"+cache.get(key1).getObjectValue());  
		        		
		        	}
	        	 }
	        	
	            Element element = cache.get(key);  
	            if (element != null) {  
	                return element.getObjectValue();  
	            }  
	        }  
	        return null;  
	    }  
	  
	    public static void put(String cacheName, Object key, Object value) {  
	        Cache cache = getCache(cacheName);  
	        if (cache != null) {  
	            cache.put(new Element(key, value));  
	        }  
	    }  
	  
	    public static boolean remove(String cacheName, Object key) {  
	        Cache cache = getCache(cacheName);  
	        if (cache != null) {  
	            return cache.remove(key);  
	        }  
	        return false;  
	    }  
	    public static void  flush(String cacheName) {  
	    	Cache cache = getCache(cacheName);  
	    	if (cache != null) {  
	    		 cache.flush();    
	    	}  
	    }  
	    
	    
	  
	    public static void main(String[] args) {  
	        String key = "key";  
	        String value = "hello";  
	        CacheUtils.put("mytest", key, value);  
	        System.out.println(CacheUtils.get("mytest", key));  
	    }  
	  
	/**
	 * Get a Cache, if not, display the log.
	 * @param cacheName
	 * @return
	 */
	private static Cache getCache(String cacheName){
		Cache cache = cacheManager.getCacheManager().getCache(cacheName);
		if (cache == null){
			throw new RuntimeException("The cache ""+cacheName+"" is not defined in the current system.");
		}
		return cache;
	}

}

 Write cache code:

 

 

//TODO can compare the date in the cache with the maximum date here
//Cache the maximum date to disk (to prevent the server from shutting down). If not closed, the maximum date value is still in the external static variable
CacheUtils.put(cacheName, cacheKeyName,maxBjsj);
//See if persistence is successful
org.springframework.util.Assert.isTrue(comparDate(((AtomicReference<Date>)CacheUtils.get(cacheName, cacheKeyName)).get(), maxBjsj.get())==0 , "cache date and just date should be equal");
					
CacheUtils.flush(cacheName);

 Read cache code:

 

 

static{
		if(CacheUtils.get(Contants.jq_maxDateCache, Contants.jq_maxDate_key) == null){
			maxBjsj = new  AtomicReference<Date>();
		}else{
			maxBjsj = (AtomicReference<Date>)CacheUtils.get(Contants.jq_maxDateCache, Contants.jq_maxDate_key);
		}
	}

 这时候,如果server关闭再开启,会读不到数据。

 

解决:

 

 

1、we.xml 加入

 <listener> <listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class> </listener>

 让服务器关闭时候,调ehcache的shutdown方法。

 

2、spring 启动的时候

System.setProperty(net.sf.ehcache.CacheManager.ENABLE_SHUTDOWN_HOOK_PROPERTY,"true");

 

 

public class SpringInit implements InitializingBean, ServletContextAware{
	private static Logger logger = LoggerFactory.getLogger(SpringInit.class);
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		
		logger.debug("-----init-----");
		System.setProperty(net.sf.ehcache.CacheManager.ENABLE_SHUTDOWN_HOOK_PROPERTY,"true");

		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		
	}

}

 再把该BEAN配置到applicationContext.xml里面

 <bean class="jiangdu.fire.util.wj.SpringInit">  
	 </bean>  

 。如果还不行可以改源码,修改DiskStorageFactory.DiskStorageFactory(..)方法,注释掉最后的 else if,让其不删除.index文件。

 

 

我这样就可以了。然后,server运行时候,.data文件是0kb的,server关闭后,.data文件就有内容了。。。不明所以

 

 可以参考:http://blog.csdn.net/kingofworld/article/details/44751029

 

 

 ----

但是运行一段时间后,在put缓存的时候,会报EOFException,但是我对象都序列化了啊。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484911&siteId=291194637