ehcache使用

来源:互联网 发布:香港有线电视台软件 编辑:程序博客网 时间:2024/05/01 08:14
在“Struts2开发,自定义标签的使用——编码自动转化为中文含义”发现,编码转换有点慢,页面像帷幕一样缓缓显示,问题主要是由于后台处理服务类拿到编码ID去数据库中查询到相应的编码中文含义,每一个ID都要如此的操作,当然数据展现比较慢,所以可能需要进一步的优化,于是第一时间就想到缓存机制。通过缓存来优化数据的获取效率。
         采用的是ehcache 缓存,需要引入ehcache.jar 支持包。主要就是优化数据库操作层的代码。
1、定义缓存工具类 EhcacheUtil.java:
package lsxy.report.tool;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
public class EhcacheUtil {
 private EhcacheUtil() {
 }
 private static CacheManager cacheManager = null;
 static {
  try {
   cacheManager = CacheManager.create();
  } catch (CacheException e) {
   e.printStackTrace();
  }
 }
 public static CacheManager getCacheManager() {
  return cacheManager;
 }
}
 
2、数据库操作层类代码引入ehcache 后的优化:
public class ReportCodeDao {
 private BasicDB db = new BasicDB();
 /**
  * 根据codeId获取对应的名称
  * 
  * @param cid
  * @return
  * @throws CacheException
  * @throws IllegalStateException
  */
 public String getCodeDesc(String cid) throws Exception {
  String codedesc = "";
  // 获取CacheManager
  CacheManager cacheManager = EhcacheUtil.getCacheManager();
  // 用配置文件中配置的colorcache创建cache缓存
  Cache cache = cacheManager.getCache("codeCache");
  // 查看cache中是否存在cid的缓存
  Element element = cache.get(cid);
  // 如果不存在,从数据库中查询
  if (element == null) {
   String sql = "select codedesc from TBL_REPORT_CODEDESC where cid='"
     + cid + "'";
   // System.out.println("从数据库中查询!" + sql);
   ResultSet rs = db.executeQuery(sql);
   try {
    if (rs.next())
     codedesc = rs.getString("codedesc");
   } catch (SQLException e) {
    e.printStackTrace();
   } finally {
    db.closed();
   }
   cache.put(new Element(cid, codedesc));
  } else {// 如果存在,从缓存中加载
   // System.out.println("从缓存中加载!");
   codedesc = element.getValue().toString();
  }
  // System.out.println("codedesc:" + codedesc);
  return codedesc;
 }
 
3、缓存配置文件ehcache.xml
<ehcache>
 <diskStore path="java.io.codeFile" />
 <defaultCache maxElementsInMemory="10000" eternal="false"
  timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
 <cache name="codeCache" maxElementsInMemory="10000" eternal="true"
  timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
</ehcache>
<!--
下列属性是 defaultCache 必须的,具体 说明: 
 maxElementsInMemory: 设定内存中创建对象的最大值;
 
             eternal:设置内存中对象是否永久驻留。如果为true,对象永不消亡;
             
   timeToIdleSeconds:设置元素消亡前的停顿时间,也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。
                         这只能在元素不是永久驻留时有效。如果该值是 0 ,就意味着元素可以停顿无穷长的时间。
                         
   timeToLiveSeconds:设置元素消亡前的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效。
   
      overflowToDisk:设置当内存中缓存达到 maxElementsInMemory 限制时元素是否可写到磁盘上。 
-->
0 0
原创粉丝点击