Spring ehcache 之"城市"缓存

Spring ehcache 之"城市"缓存
      先描述下我的环境eclipse 3.2.2+myeclilpse 5.5.1
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 );
        
    }
}


有什么不足的地方请高人指点

你可能感兴趣的:(Spring ehcache 之"城市"缓存)