Spring整合Ehcache

一. maven添加Ehcache的依赖jar包:

<!--ehcache 相关包 -->
   <dependency>
       <groupId>net.sf.ehcache</groupId>
       <artifactId>ehcache</artifactId>
       <version>2.7.5</version>
   </dependency>
   <dependency>
       <groupId>com.googlecode.ehcache-spring-annotations</groupId>
       <artifactId>ehcache-spring-annotations</artifactId>
       <version>1.2.0</version>
   </depenency>

二. 项目中创建ehcache.xml文件,配置cache的相关信息:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false">
    <!--
        磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
        path:指定在硬盘上存储对象的路径
    -->
    <!--<diskStore path="java.io.tmpdir"/>-->
    <diskStore path="E:\\cache"/>

    <!-- Cluster localhost setting -->
    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
       multicastGroupPort=4446, timeToLive=32"/>

    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
            properties="hostName=localhost, port=40001,socketTimeoutMillis=2000"/>

    <!--
        maxElementsInMemory设置成1,overflowToDisk设置成true,只要有一个缓存元素,就直接存到硬盘上去
        eternal设置成true,代表对象永久有效
        maxElementsOnDisk设置成0 表示硬盘中最大缓存对象数无限大
        diskPersistent设置成true表示缓存虚拟机重启期数据
     -->
    <!--根据需要配置自定义cache-->
    <cache name="dictCache" maxElementsInMemory="1" overflowToDisk="true"
           eternal="true">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicatePuts=false,replicateUpdatesViaCopy=false"/>
    </cache>
    <!--根据需要配置自定义cache-->
    <cache name="eternalCache" maxElementsInMemory="100"
           overflowToDisk="true" eternal="false" timeToIdleSeconds="1200"
           timeToLiveSeconds="1200">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicatePuts=false,replicateUpdatesViaCopy=false"/>
    </cache>
    <!-- DefaultCache setting. Modify ehcache-safe.xml for timeToIdleSeconds,timeToLiveSecond,diskExpiryThreadIntervalSeconds
        Use ehcache-safe.xml default for maxElementsInMemory,maxElementsOnDisk,overflowToDisk,eternal
        Use ehcache default for memoryStoreEvictionPolicy,diskPersistent,. -->
    <!--
     defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
     maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
     eternal:代表对象是否永不过期
     overflowToDisk:当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
-->
    <defaultCache maxElementsInMemory="10000"
                  overflowToDisk="true"
                  eternal="false"
                  memoryStoreEvictionPolicy="LRU"
                  maxElementsOnDisk="10000000"
                  diskExpiryThreadIntervalSeconds="600"
                  timeToIdleSeconds="3600"
                  timeToLiveSeconds="100000"
                  diskPersistent="false"/>
</ehcache>

三. Spring管理ehcache相关配置,spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
      http://cxf.apache.org/jaxws 
          http://cxf.apache.org/schemas/jaxws.xsd
      http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
     <!-- 自动扫描包-->
    <!--数据源配置信息-->
    <!--事物管理配置-->

    <!--方式一: 注解方式配置-->
   <cache:annotation-driven cache-manager="cacheManager" />

   <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
      <property name="cacheManager" ref="ehcache"></property>
   </bean>

   <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
      <property name="configLocation" value="classpath:ehcache.xml"></property>
   </bean>
    <!--方式二:通过CacheManager方式-->

</beans>

实例:

//新增
/**
    使用注解时,value值对应ehcache.xml中caache的name
*/
//@Cacheable(value = "dictCache", key = "'test_' + '#entity.getId'")
public Serializable save(TestDemoEntity entity) throws Exception{
    //通过 CacheManager创建cache对象   
    CacheManager cacheManager = CacheManager.getInstance();
    //getCache(param),param参数对应ehcache.xml文件中cache的name的值
    Cache dictCache = cacheManager.getCache("dictCache");
    //通过Element对象设置要存储的key=value
    Element element = new Element(key,value);
    dictCache.put(element);
    List keys = dictCache.getKeys();
    Serializable t = super.save(entity);
    this.doAddBus(entity);
    return t;
}
//删除
//@CacheEvict(value = "dictCache",key = "'test_' + '#entity.getId'")
public void delete(TestDemoEntity entity) throws Exception{
    CacheManager cacheManager = CacheManager.getInstance();
    Cache dictCache = cacheManager.getCache("dictCache");
    //判断要删除的key是否在缓存中
    if(dictCache.isElementInMemory(key)){
       dictCache.remove(key);
    }
    super.delete(entity);
    this.doDelBus(entity);
}
//获取cache中keys
public void getCacheKeys() throws Exception{
    CacheManager cacheManager = CacheManager.getInstance();
    Cache dictCache = cacheManager.getCache("dictCache");
    //查询cache中所有的key
    List list = dictCache.getKeys();
    //查询cache中key的数量
    Integer count = dictCache.getSize();
}
//根据key获取value
private void getValue(String key) throws Exception{
    CacheManager cacheManager = CacheManager.getInstance();
    Cache dictCache = cacheManaher.getCache("dictCache");
    //通过get(key)方法获取到的是Element对象
    Element element = dictCache.get(key);
    //element获取value有两种方式
    //第一种:获取到的vlaue的类型时Serializable 
    Serializable value = element.getValue();
    //第二种:获取到的value的类型为Object
    Object obj = element.getObjectValue();
   }

 

转载于:https://my.oschina.net/u/3544283/blog/1809975

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值