隨筆-153  評論-235  文章-19  trackbacks-0
                先描述下我的環境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);
                  
              }
          }


          有什么不足的地方請高人指點
          posted on 2007-08-02 14:35 流浪汗 閱讀(3145) 評論(1)  編輯  收藏 所屬分類: OpenSource

          評論:
          # re: Spring ehcache 之"城市"緩存 2008-02-20 17:43 | kuan
          會不會有點太過嵌入的味道?  回復  更多評論
            
          主站蜘蛛池模板: 台中市| 兴仁县| 凤山市| 同心县| 新野县| 花莲县| 张家港市| 湖北省| 南陵县| 商城县| 岳普湖县| 交城县| 蕲春县| 珠海市| 洞头县| 石台县| 绍兴县| 乐安县| 枞阳县| 稷山县| 唐山市| 山东| 大埔区| 永宁县| 利辛县| 吉林省| 南充市| 缙云县| 鹰潭市| 右玉县| 渝北区| 武义县| 宜良县| 宁夏| 尼勒克县| 惠来县| 巩义市| 类乌齐县| 塔河县| 孟州市| 禄丰县|