Spring 2.0.6,Ehcache用spring2.0.6带的1.2.4
加入的jar
Spring.jar
commons-logging.jar
ehcache-1.2.4.jar
log4j-1.2.14.jar
junit3.8.1.jar
示例描述:通过省ID找它下面的市,缓存市.
1.我用IdAndName类封装市,可以替换成String.
package com.chenlb.study.ehcache;
/**
* 2007-8-2
* @author chenlb
*
*/
public class IdAndName {
private Integer id;
private String name;
public IdAndName() {}
/**
* @param id
* @param name
*/
public IdAndName(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.定义一个接口CityCache
package com.chenlb.study.ehcache;
import java.util.List;
/**
* 2007-8-2
* @author chenlb
*
*/
public interface CityCache {
public List<IdAndName> getCitys(Integer provinceId);
}
3.定义数据类CityData,
/*
*
*/
package com.chenlb.study.ehcache;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 2007-8-2
* @author chenlb
*
*/
public class CityData {
static Map<Integer, List<IdAndName>> provinces = new HashMap<Integer, List<IdAndName>>();
static {
ArrayList<IdAndName> al = new ArrayList<IdAndName>(); //广东
al.add(new IdAndName(1,"广州市")); al.add(new IdAndName(2,"梅州市"));
provinces.put(1, al);
al = new ArrayList<IdAndName>(); //上海
al.add(new IdAndName(1,"黄浦")); al.add(new IdAndName(2,"卢湾"));
provinces.put(2, al);
}
/**
* 此方法可以换成从数据库得到数据
* @param provinceId
* @return
*/
public static List<IdAndName> getCityByProvince(Integer provinceId) {
return provinces.get(provinceId);
}
}
4.市缓存实现CityCacheMemoryImpl
/*
*
*/
package com.chenlb.study.ehcache;
import java.util.List;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 2007-8-2
* @author chenlb
*
*/
public class CityCacheMemoryImpl implements CityCache{
private static final Log logger = LogFactory.getLog(CityCacheMemoryImpl.class);
private Cache cityCache;
/* (non-Javadoc)
* @see com.chenlb.study.ehcache.CityCache#getCitys(java.lang.Integer)
*/
public List<IdAndName> getCitys(Integer provinceId) {
// TODO Auto-generated method stub
Element element = cityCache.get(provinceId);
if(element == null) {
List<IdAndName> lt = CityData.getCityByProvince(provinceId);//可以认为是数据查询
element = new Element(provinceId, lt);
cityCache.put(element);
if(logger.isInfoEnabled()) {
logger.info("城市加载到缓存");
}
}
return (List<IdAndName>) element.getValue();
}
public void setCityCache(Cache cityCache) {
this.cityCache = cityCache;
}
}
说明:getcitys()方法重要,要加载没有的内容
5.ehcache.xml同时把ehcache.xsd放到同一目录
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<cache name="cityCache"
maxElementsInMemory="10" //最大缓存10个对象
eternal="false" //不是永久有效
overflowToDisk="false" //缓存满了不写的磁盘
timeToIdleSeconds="1" //1秒后没有读就失效
timeToLiveSeconds="2" //2秒后失效
memoryStoreEvictionPolicy="LFU"
/>
</ehcache>
6.Spring 配置文件夹applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation"
value="classpath:com/chenlb/study/ehcache/ehcache.xml">
</property>
</bean>
<bean id="cityCacheBean" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager"></property>
<property name="cacheName" value="cityCache"></property>
</bean>
<bean id="cityCache" class="com.chenlb.study.ehcache.CityCacheMemoryImpl">
<property name="cityCache" ref="cityCacheBean"></property>
</bean>
</beans>
7.测试用例CityCacheTest
/*
*
*/
package com.chenlb.study.ehcache;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 2007-8-2
* @author chenlb
*
*/
public class CityCacheTest extends TestCase {
protected final Log logger = LogFactory.getLog(getClass());
private ApplicationContext context;
private Random random;
/**
* @throws java.lang.Exception
*/
protected void setUp() throws Exception {
context = new ClassPathXmlApplicationContext(
new String[] {"application*.xml"}
);
random = new Random();
}
/**
* @throws java.lang.Exception
*/
protected void tearDown() throws Exception {
}
/**
* Test method for {@link com.chenlb.study.ehcache.CityCache#getCitys(java.lang.Integer)}.
*/
public void testGetCitys() {
CityCache cityCache = (CityCache) context.getBean("cityCache");
List<IdAndName> citys = cityCache.getCitys(1);
assertNotNull(citys);
assertTrue(citys.size() > 0);
for(IdAndName inn : citys) {
logger.info("省1 : "+inn.getName());
}
citys = cityCache.getCitys(2);
assertNotNull(citys);
assertTrue(citys.size() > 0);
for(IdAndName inn : citys) {
logger.info("省2 : "+inn.getName());
}
}
public void testGetCitysWithLoop() {
CityCache cityCache = (CityCache) context.getBean("cityCache");
List<IdAndName> citys, citys_2;
int loopNum = 5;
int totelTimes = 0;
do {
logger.info("===============第 "+(6-loopNum)+"次循环===============");
citys = cityCache.getCitys(1);
assertNotNull(citys);
assertTrue(citys.size() > 0);
for(IdAndName inn : citys) {
logger.info("省1 : "+inn.getName());
}
citys_2 = cityCache.getCitys(2);
assertNotNull(citys_2);
assertTrue(citys_2.size() > 0);
for(IdAndName inn : citys_2) {
logger.info("省2 : "+inn.getName());
}
loopNum --;
try {
int times = random.nextInt(800) + 400;//400 - 1200 ms
Thread.sleep(times);
totelTimes += times;
logger.info(totelTimes + " ms 后, 间隔: "+times+" ms");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}while(loopNum > 0);
loopNum = 5;
do { //省2
logger.info("===============第 "+(6-loopNum)+"次循环===============");
citys = cityCache.getCitys(2);
assertNotNull(citys);
assertTrue(citys.size() > 0);
for(IdAndName inn : citys) {
logger.info("省2 : "+inn.getName());
}
loopNum --;
try {
int times = random.nextInt(400) + 400;//400 - 800 ms
Thread.sleep(times);
totelTimes += times;
logger.info(totelTimes+" ms 后, 间隔: "+times+" ms");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}while(loopNum > 0);
}
}
分享到:
相关推荐
springboot 使用spring cache缓存 和 使用fastjson配置redis系列化,springboot 使用spring cache缓存 和 使用fastjson配置redis系列化,springboot 使用spring cache缓存 和 使用fastjson配置redis系列化,springboot ...
redis与springcache集成,对应的文章可以在我的csdn博客中找到
承接上个代码将memecached调用改为交给Spring Cache代理
redis主从配置流程,关键配置项,哨兵模式实现高可用。并整合spring cache功能。快速方便
之前整合springcache+redis的时候到网上搜了很多代码方案,但是注解都不起作用,搞了很长时间,也是很郁闷。所以,把成果分享一下,避免更多人踩坑,哈哈
简单的实现了spring cache,包括第一次存入缓存,缓存查询和缓存清空等等
自己开发过程中使用到的一片Spring Cache 技术文档,很实用,
SpringCache与redis集成,优雅的缓存解决方案.docx
1、SpringCache是Spring提供的一个缓存框架,在Spring3.1版本开始支持将缓存添加到现有的spring应用程序中,在4.1开始,缓存已支持JSR-107注释和更多自定义的选项 2、Spring Cache利用了AOP,实现了基于注解的缓存...
spring cacke spring cacke
Redis-Cluster集群整合SpringCahe的一个demo,将redis作为缓存,解决分布式问题
本文是springboot 使用spring cache缓存 和 缓存数据落地到redis的研究笔记,为方便下载查看,特意分享了springboot 使用spring cache缓存 和 缓存数据落地到redis.pdf的文件。希望搭建对springboot 使用spring ...
spring-cache-mongodb:基于MongoDB的Spring Cache实现
SpringCache整合Redis简单练习
这篇我们讲讲怎么使用SpringCache中的@CachePut。 功能说明 我们在日常使用缓存的时候,不仅需要添加缓存、删除缓存,更需要更新缓存。Springcache中如何来实现缓存的更新呢?不错,@CachePut就能帮助我们来实现...
Spring Cache 复合缓存管理器
SpringCache缓存初探共5页.pdf.zip
关于Spring Cache 在Spring3.1以后增加了一项happy的技术点,就是基于注解来实现缓存的技术。他的本质上不是具体的缓存方案实现,而是一个对缓存的抽象,让我们通过注解,实现少量的代码,达到实现缓存的方案。 ...
springboot_springcache_redis入门实例,共同学习进步
通过spring-cache对方法进行缓存,同时验证如何通过key更新指定的缓存!