使用Ehcache与SapphireCache(转载)

欢迎去看原著,转载来自于:
引用
http://www.iteye.com/topic/1125445

先说Ehcache吧,比较常用,配置简单,性能也可以
Hibernate缺省的缓存框架,下载的话网上一搜一大把,首先的话需要导入Ehcache所需jar包,然后配置配置文件:
<?xml version="1.0" encoding="UTF-8"?>   
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"  
    updateCheck="false">   
    <diskStore path="java.io.tmpdir" />   
  
    <!-- 用户账号缓存 -->   
    <cache name="accountCache" eternal="false" maxElementsInMemory="1000"  
        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"  
        timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU">   
    </cache>   
</ehcache>  




使用Ehcache:

/* 声明缓存管理容器 */  
CacheManager cm = new CacheManager("info-cache.xml");   
           
/* 获取缓存实例 */  
Cache cache = cm.getCache("accountCache");   
cache.put(new Element("account", "zhangsan"));   
System.out.println(cache.get("account").getValue());  



从上述示例中我们可以看出,Ehcache的基本使用比较简单,接下来,我们再次演示另外一种缓存框架,SapphireCache。SapphireCache是一种新缓存框架,感觉配置和使用上更为简单和方便,避免了很多不必要的层次封装,降低资源开销的同时,还提升了很强的缓存吞吐性与分布式缓存的并发性。
导入配置文件:

<?xml version="1.0" encoding="UTF-8"?>   
<!DOCTYPE sapphire PUBLIC    
    "-//Sapphire Cache//DTD Sapphire Configuration 1.1//CN"  
    "http://sapphire-cache.googlecode.com/files/sapphire-cache-1.1.9.dtd">   
<sapphire>   
    <!-- 缓存注解服务驱动 -->   
    <service:annotation-driven auto="true" />   
  
    <!-- 缓存持久化全局配置 -->   
    <diskStore path="java.io.tmpdir" diskEternal="false"  
        timeToRemoveSeconds="60" />   
  
    <!-- 缺省缓存配置 -->   
    <cache eternal="false" maxElementsInSize="100" maxCacheInMemory="1"  
        capacityUnit="kByte" overflowToDisk="true" diskPersistent="false"  
        timeToLiveSeconds="60" cacheCleanupPolicy="FIFO">   
    </cache>   
</sapphire>  



使用示例:
/* 初始化缓存管理容器 */  
CacheManager cacheManager = new SapphireCacheManager();   
           
/* 获取缓存实例 */  
Cache cache = cacheManager.getCache("defaultCache");   
cache.put("account", "admin");   
System.out.println(cache.get("account"));  

猜你喜欢

转载自fantaoyalin.iteye.com/blog/1607990