服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

利用缓存机制快速读取xml文件中的数据

接到一个任务,让我做一个公司网站的后台管理系统。要求很简单,就一个新闻发布模块和一个招聘信息发布模块。但不能用db,只能用文件存取的形式实现。

       不用考虑肯定是用xml文件进行数据的存取了,以前做毕设的时候也曾经实现过类似的功能,所以关于xml的读取并没有问题。关键是如果考虑到性能的问题就值得推敲一下了,我是新人,以前也没做过什么设计,所以做出的东西在一些人眼中可能会有些稚嫩,那也没关系,走自己的路让别人去说吧:)

       如果频繁解析文件,速度肯定受到影响,在文件非常大的情况下,甚至是无法忍受的。如果在服务器启动的时候先把文件中的数据封装成对象数组读入到缓存中,每次访问的时候先判断一下要访问的文件实体有没有被更新,如果没有被更新,就直接从缓存中将想要的数据读出来,当然如果文件被更新了,那只好老老实实的解析文件读出想要的数据。管理者对文件的修改次数毕竟是少数,更多的是访问者的访问次数。这样就能很大的提高了访问速度,代价是要占用一定的内存空间,但相比之下应该算小巫吧。

        下面把简单实现的几个class说一说。

        一 首先实现一个cache类,里面有读取对象的方法get(),如果文件没有被修改则直接从hashmap里面将对象取出,如果文件被修改则调用readobject()方法实现从文件中读出数据,并同时将读出的数据放入hashmap里,将原来的对象覆盖。这样下次再读数据的时候就可以从缓存中直接读到,并且保证是最新的数据。还有一个判断文件是否被修改的方法getmodified();
代码实现如下:

import java.io.file;
import java.util.hashmap;

public class cache {
    
    hashmap maplastmodified = new hashmap();
    hashmap mapvalues = new hashmap();
    public cache() {
        super();
    }    
    public object get(string name, string path, class clsparser, class clsinstantiator, class clsobj) {
        object obj = null;
        string abspath = getclass().getresource(path).getpath();        
        long modified = getmodified(name, abspath);
        if (modified != null) {
            obj = readobject(abspath, clsparser, clsinstantiator, clsobj);
            
            maplastmodified.put(name, modified);
            mapvalues.put(name, obj);
            system.out.println("get object from file");
        } else {
            obj = mapvalues.get(name);
            system.out.println("get object from cache");
        }       
        return obj;
    }
    
    private long getmodified(string name, string path) {
        long modified = new long(new file(path).lastmodified());
        long savemodified = (long) maplastmodified.get(name);
        if ((savemodified != null) && (savemodified.longvalue() >= modified.longvalue())) {
            modified = null;
        }        
        return modified;
    }
    
    private object readobject(string path, class clsparser, class clsinstantiator, class clsobj) {
        try {
            fileparser parser = (fileparser) clsparser.newinstance();
            instantiator instantiator = (instantiator) clsinstantiator.newinstance();

            object config = parser.parse(path);            
            return instantiator.instantiate(clsobj, config);
            
        } catch (instantiationexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        }       
        return null;
    }
}

二 解析xml文件的类xmlfileparser,
为了方便处理不同文件的解析,在这里先定义一个接口fileparser,xmlfileparser实现了它,如果还有诸如对其他种类文件的解析也可以实现它。
//fileparser.java
public interface fileparser {
    object parse(string path);

}

//xmlfileparser.java
//采用jdom的解析方式

import java.io.fileinputstream;
import java.io.ioexception;
import org.jdom.document;
import org.jdom.element;
import org.jdom.input.saxbuilder;

public class xmlfileparser implements fileparser {

 public xmlfileparser() {
  super();
 }

 public object parse(string path) {
  
  fileinputstream fi = null;
  try {
   fi = new fileinputstream(path);
   saxbuilder sb = new saxbuilder();
   document doc = sb.build(fi);
   element root = doc.getrootelement();
   return root.getchildren();
  } catch (exception e) {
   e.printstacktrace();
  } finally {
   try {
    fi.close();
   } catch (ioexception e1) {
   }
  }  
 }
}

三 接下来是一个实例化处理的类listtypeinstantiator,同样为了方便处理不同文件的实例化,在这里先定义一个接口instantiator,listtypeinstantiator实现了它。
//instantiator.java
public interface instantiator {
    object instantiate(class clazz, object configuration);
}

//listtypeinstantiator.java
import java.util.arraylist;
import java.util.list;

import org.apache.commons.beanutils.beanutils;
import org.jdom.element;

public class listtypeinstantiator implements instantiator {

 public listtypeinstantiator() {
  super();
 }

 public object instantiate(class clazz, object configuration) {
  list arr = new arraylist();
  object bean = null;
    
  list children = (list) configuration;
  element child = null;

  list attributes = null;
  element attribute = null;
  
  try { 
   for(int i=0; i    child = (element) children.get(i);
    bean = clazz.newinstance();   
    attributes = child.getchildren();
    for(int j=0; j     attribute = (element) attributes.get(j);
     beanutils.setproperty(bean, attribute.getname(), attribute.gettext());
    }   
    arr.add(bean);
   }
  } catch(exception e) {
   e.printstacktrace();
  }  
  return arr;
 }
}

四 另外还需要一个封装我想要数据形式的javabean,这里设为newsbean{}.
//newsbean.java
public class newsbean {

 private long id;
 private string newstitle;
 private string newscontent;
 private string newstype;
 private string deploydate;
 private string canceldate;
    
 public long getid() {
  return id;
 }
 public void setid(long id) {
  this.id = id;
 }   
 public string getnewstitle() {
  return newstitle;
 }
 public void setnewstitle(string newstitle) {
  this.newstitle = newstitle;
 }
 public string getnewscontent() {
  return newscontent;
 }
 public void setnewscontent(string newscontent) {
  this.newscontent = newscontent;
 }
 public string getnewstype() {
  return newstype;
 }
 public void setnewstype(string newstype) {
  this.newstype = newstype;
 }
 public string getdeploydate() {
  return deploydate;
 }
 public void setdeploydate(string deploydate) {
  this.deploydate = deploydate;
 }
 public string getcanceldate() {
  return canceldate;
 }
 public void setcanceldate(string canceldate) {
  this.canceldate = canceldate;
 } 
}

五 最后一步测试结果,将news.xml文件放到classes目录下。
//mainclass.java

import java.util.list;
public class mainclass{

 public static void main(string[] args) throws exception {

  list news1 = null;
  list news2 = null;
  newsbean bean = null;

  news1 = (list)cache.get(
   "news", "/news.xml", 
      xmlfileparser.class, listtypeinstantiator.class, newsbean.class);  
  for (int i = 0; i < news1.size(); i++) {
   bean = (newsbean) news1.get(i);
   system.out.println(bean.getid());
   system.out.println(bean.getnewstitle());
   system.out.println(bean.getnewscontent());
   system.out.println(bean.getnewstype());
   system.out.println(bean.getdeploydate());
   system.out.println(bean.getcanceldate());
  } 
  news2 = (list)cache.get(
   "news", "/news.xml", 
      xmlfileparser.class, listtypeinstantiator.class, newsbean.class);  
  for (int i = 0; i < news2.size(); i++) {
   bean = (newsbean) news2.get(i);
   system.out.println(bean.getid());
   system.out.println(bean.getnewstitle());
   system.out.println(bean.getnewscontent());
   system.out.println(bean.getnewstype());
   system.out.println(bean.getdeploydate());
   system.out.println(bean.getcanceldate());
  }
}
第一次会从文件中读出数据,第二次就会从缓存中读取了,试着多读几次速度明显快很多。