Ehcache学习(二)整合spring

下面结合spring使用ehcache!

需要引入Ehcache和spring相关的jar包:

这里写图片描述

Ehcache配置文件:


<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false">

    <diskStore path="java.io.tmpdir" />
    <defaultCache maxElementsInMemory="100000" eternal="false"
        overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120"
        diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LFU" />
    <!--这里设置了缓存失效时间10秒(timeToLiveSeconds)-->
    <cache name="testCache" maxElementsInMemory="20000" eternal="false"
        overflowToDisk="false" timeToIdleSeconds="1800" timeToLiveSeconds="10"
        memoryStoreEvictionPolicy="LFU">
    </cache>

</ehcache>

Spring配置文件:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms-2.5.xsd" >

    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation">
            <value>classpath:ehcache.xml</value>
        </property>
    </bean>
</beans>

使用:

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

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class EhCacheSpringTest {
     public static void main(String[] args) {
        String ecacheName="testCache";
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        CacheManager cacheManager=(CacheManager)ctx.getBean("ehcacheManager");
        Cache cache=cacheManager.getCache(ecacheName);
        //存缓存
        Element element=new Element(ecacheName, "Hello Cache33!");
        cache.put(element);
        //取缓存
        Element el=cache.get(ecacheName);
        String value=el.getObjectValue().toString();
        System.out.println(value);

    }

}

[源码下载]:(http://pan.baidu.com/s/1i5qTIAx)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值