日期:2014-05-19  浏览次数:20719 次

j2ee缓存——小了解

个人认为适宜在不经常修改的大批量读取数据库数据时应用。


仅以我读取一个区域内容的情况为例:


(1)在service类中实例化静态HashMap
??? private static HashMap<Long,String> areaNamehash =new HashMap<Long,String>();
(2)在service类中创建其setter方法
??? public static void setAreaNamehash(HashMap<Long, String> areaNamehash)
??? {
??????? AreaService.areaNamehash = areaNamehash;
??? }
(3)在service类中创建action可使用的方法(如果缓存中已有值则应用缓存中值,如没有则通过DAO从数据库中取出)
??? public String getAreaName(int compId, long areaId)
??? {
??????? String areaName = areaNamehash.get(areaId);
??????? if(areaName == null || "".equals(areaName))
??????? {
??????????? List<Areas> areas = dao.getAllAreaByComId(compId);
??????????? for (Areas ar : areas) {
????????????? long id = ar.getAreasid();
????????????? String name = ar.getAreaname();
????????????? areaNamehash.put(id, name);
??????????? }
??????????? areaName = areaNamehash.get(areaId);
??????? }
??????? return areaName;
??? }
(4)在service类中创建destroy方法,用来释放缓存
??? public void destroy()
??? {
??????? areaNamehash.clear();
??? }


(5)创建随服务器启动的servlet类
<servlet>
?? <deion>load all cache</deion>
?? <servlet-name>loadCache</servlet-name>
?? <servlet-class>com.wiwj.util.cache.DoLoadCache</servlet-class>
?? <load-on-startup>1</load-on-startup>
</servlet>
(6)实例化主体LoadCache类,运行其加载缓存的方法,方法具体模式如下:
a、实例化缓存的HashMap
??? HashMap<Long, String> areahash = new HashMap<Long, String>();
b、用方法将数据库中取出的信息通过DAO装入HashMap中
????? this.loadAreaCache(compId, areahash);
??????? //方法如下
????????? private void loadAreaCache(int compId, HashMap<Long, String> hash) {
??????????? AreaDAO dao = new AreaDAO();
??????????? List<Areas> areas = dao.getAllAreaByComId(compId);
??????????? for (Areas ar : areas) {
????????????? long id = ar.getAreasid();
????????????? String name = ar.getAreaname();
????????????? hash.put(id, name);
??????????? }
????????? }
c、用service类中的setter方法将上面的HashMap装入service类中的静态HashMap中
??? AreaService.setAreaNamehash(areahash);
(7)在LoadCache类中创建destroy方法,调用service类中的destroy方法,释放缓存
public void destroy() {
??? AreaService.getInstance().destroy();
}
(8)在servlet类中调用LoadCache类中的destroy方法,释放内存

?