ehcache实践

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">


    <diskStore path="temp.data"/>


  <!--   <cacheManagerEventListenerFactory class="" properties=""/>


    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1"
            propertySeparator=","
            />


    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/> -->


    <defaultCache
            maxElementsInMemory="2"
            eternal="true"
            timeToIdleSeconds="1"
            timeToLiveSeconds="1"
            overflowToDisk="false"
            memoryStoreEvictionPolicy="LRU"
            />
    <!--  name:缓存名称  
     maxElementsInMemory:内存中最大缓存对象数  
     maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大  
     eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false  
     overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。  
     diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。  
     diskPersistent:是否缓存虚拟机重启期数据  
     diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒  
     timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态  
     timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义  
     memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。  -->
     <cache name="appFileCache"  
           maxElementsInMemory="1000000"  
           eternal="true"  
           overflowToDisk="false" 
           diskSpoolBufferSizeMB="512" 
           maxElementsOnDisk="10000000"
           diskPersistent="true" 
           diskExpiryThreadIntervalSeconds="120" 
           memoryStoreEvictionPolicy="LRU"
     /> 
<cache name="appFilesCache"  
          maxElementsInMemory="1000000"  
          eternal="true"  
          overflowToDisk="false" 
          diskSpoolBufferSizeMB="512" 
          maxElementsOnDisk="10000000"
          diskPersistent="true" 
          diskExpiryThreadIntervalSeconds="120" 
          memoryStoreEvictionPolicy="LRU"
    /> 
</ehcache>


package org.ivce.commons.cache;



import java.util.ArrayList;
import java.util.List;
import java.util.Map;


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


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class CommonCache<K,V> {
private static Logger logger = LoggerFactory.getLogger(CommonCache.class);
private static CacheManager manager;
private Cache cache ;

static{
System.setProperty("net.sf.ehcache.enableShutdownHook","true");
manager = new CacheManager(CommonCache.class.getClassLoader().getResource("ehcache.xml"));
// cache = manager.getCache("app");
}

public CommonCache(String cacheName) {
cache = manager.getCache(cacheName);
}

public CommonCache() {
}


public void clearAll(){
if(cache != null)
cache.removeAll();
}

public int getSize(){
try {
if(cache != null)
return cache.getSize();
} catch (Exception e) {
logger.error("get cache size error!", e);
e.printStackTrace();
}
return 0;
}

public <V> void putValue(K key,V val){
try {
if(cache != null)
cache.put(new Element(key, val));
} catch (Exception e) {
logger.error("put cache data error!", e);
e.printStackTrace();

}

public <V> V getValue(K key){
try {
if(cache != null && cache.isKeyInCache(key)){
Element element = cache.get(key);
return (V) element.getObjectValue();
}
} catch (Exception e) {
logger.error("get cache data error!", e);
e.printStackTrace();
}
return null;
}

public <V> List<V> getValues(){
List<V> list = new ArrayList<V>();
Map<Object, Element> all = null;
try {
if(cache != null)
all = cache.getAll(cache.getKeys());
if(all != null && all.size()>0){
for (Object k : all.keySet()) {
list.add((V)all.get(k).getObjectValue());
}
}
if(list.size()>0)
return list;
} catch (Exception e) {
logger.error("get cache datas error!", e);
e.printStackTrace();

return null;
}


public static void shutDown(){
manager.shutdown();
}
/*public static void main(String[] args) {
CommonCache.putValue2("1", "zs1");
CommonCache.putValue2("2", "zs2");
CommonCache.putValue2("3", "zs3");

String value = CommonCache.getValue2("2");
int size = CommonCache.getSize();
CommonCache.shutDown();
System.out.println(value);
System.out.println(size);
}
public static void main0(String[] args) {
User user1 = new User();
user1.setAge(0);
user1.setName("zs");
User user2 = new User();
user2.setAge(1);
user2.setName("ls");
User user3 = new User();
user3.setAge(3);
user3.setName("wu");

CommonCache.putValue2("1", user1);
CommonCache.putValue2("2", user2);
CommonCache.putValue2("3", user3);

int size = CommonCache.getSize();
System.out.println(size);

User value = CommonCache.getValue2("1");
System.out.println(value);

List<User> list = CommonCache.getValues();
System.out.println(list);

CommonCache.shutDown();
}*/

}


package org.ivce.commons.cache;


import java.util.ArrayList;
import java.util.List;


import org.ivce.commons.domain.AppFile;


public class AppFilesCache extends CommonCache<String,AppFile> {
private static final String CACHE_NAME = "appFilesCache";
private static AppFilesCache appFileCache;

private AppFilesCache() {
super(CACHE_NAME);
}

public static AppFilesCache getInstance(){
if(appFileCache == null){
synchronized (AppFilesCache.class) {
if(appFileCache == null){
appFileCache = new AppFilesCache();
}
}
}
return appFileCache;
}
public List<AppFile> getAppFileByAppId(String appId){
return getValue(appId);
}
public void putAppFiles(String appId,List<AppFile> appFiles){
if(appFiles != null && appFiles.size()>0)
putValue(appId, appFiles);
}

public static void main(String[] args) {
List<AppFile> appFiles = new ArrayList<AppFile>();
AppFile file = new AppFile();
file.setId(1L);
file.setAppInfoId("1");
file.setAppContent("abc");
AppFile file2 = new AppFile();
file2.setAppInfoId("1");
file2.setId(2L);
file2.setAppContent("efg");
appFiles.add(file);
appFiles.add(file2);

AppFilesCache.getInstance().putValue(file.getAppInfoId(), appFiles);

long beginTime = System.currentTimeMillis();
List<AppFile> files = AppFilesCache.getInstance().getAppFileByAppId("1");
System.out.println("查缓存耗时:"+(System.currentTimeMillis()-beginTime)+"ms.");
shutDown();
System.out.println(files);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值