package com.bdc.cache;


import java.util.HashMap;

import java.util.Map;









public class CacheTest {









private Map map = new HashMap();










public Object getValue(String key){











Object obj = map.get(key);



//先从缓存里面取值











if(obj == null){

//判断缓存里面是否有值数据














System.out.println("缓存中不存在,从数据库中取出");















obj =“The Value You Put” //模拟从数据库读取数据















map.put(key, obj);
//将取出的数据 放入缓存,以便下次从缓存取数据











}else{














System.out.println("缓存中存在此key的数据");











}











return obj;







}























public void
deleteCache(String key){










if(map.get(key)!=null){













map.remove(key);










}

















}





















public void updateCache(String key){










//模拟从数据库取出此数据










Object obj = "GetDataFromDB";










if(obj!=map.get(key)){













map.remove(key);













map.put(key, obj);










}







}









}


Junit测试-

package com.bdc.test;


import org.junit.Test;

import com.bdc.cache.CacheTest;


public class TestCache {








@Test




public void test(){







CacheTest cache = new CacheTest();







System.out.println("********************");







long t1 = System.currentTimeMillis();







String str1 = (String) cache.getValue("name");







for(int i=0;i<=10000;i++){










System.out.print("");







}







long t2 = System.currentTimeMillis();







System.out.println("str1 is :"+str1);







System.out.println("用时 :"+(t2-t1));







System.out.println("********************");







long t3 = System.currentTimeMillis();







String str2 = (String) cache.getValue("name");







for(int i=0;i<=10000;i++){










System.out.print("");







}







long t4 = System.currentTimeMillis();







System.out.println("str2 is :"+str2);







System.out.println("用时 :"+(t4-t3));







System.out.println("********************");







long t5 = System.currentTimeMillis();







String str3 = (String) cache.getValue("age");







for(int i=0;i<=10000;i++){










System.out.print("");







}







long t6 = System.currentTimeMillis();







System.out.println("str3 is :"+str3);







System.out.println("用时 :"+(t6-t5));







System.out.println("********************");




}


}


输出结果-

********************

缓存中不存在,从数据库中取出

str1 is :name baby

用时 :3

********************

缓存中存在

str2 is :name baby

用时 :1

********************

缓存中不存在,从数据库中取出

str3 is :age baby

用时 :2

********************