最近参与了github上的一个开源项目 Mycat,是一个mysql的分库分表的中间件。发现其中读取配置文件的代码,存在频繁多次重复打开,读取,关闭的问题,代码写的很初级,稍微看过一些框架源码的人,是不会犯这样的错误的。于是对其进行了一些优化。

优化之前的代码如下所示:

    private static Element loadRoot() {
InputStream dtd = null;
InputStream xml = null;
Element root = null;
try {
dtd = ConfigFactory.class.getResourceAsStream("/mycat.dtd");
xml = ConfigFactory.class.getResourceAsStream("/mycat.xml");
root = ConfigUtil.getDocument(dtd, xml).getDocumentElement();
} catch (ConfigException e) {
throw e;
} catch (Exception e) {
throw new ConfigException(e);
} finally {
if (dtd != null) {
try {
dtd.close();
} catch (IOException e) { }
}
if (xml != null) {
try {
xml.close();
} catch (IOException e) { }
}
}
return root;
}

然后其它方法频繁调用 loadRoot():

    @Override
public UserConfig getUserConfig(String user) {
Element root = loadRoot();
loadUsers(root);
return this.users.get(user);
} @Override
public Map<String, UserConfig> getUserConfigs() {
Element root = loadRoot();
loadUsers(root);
return users;
} @Override
public SystemConfig getSystemConfig() {
Element root = loadRoot();
loadSystem(root);
return system;
}
// ... ...

ConfigUtil.getDocument(dtd, xml) 方法如下:

    public static Document getDocument(final InputStream dtd, InputStream xml) throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setValidating(false);
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(dtd);
}
});
builder.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException e) {
}
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
throw e;
}
});
return builder.parse(xml);
}

显然这不是很好的处理方式。因为会多次重复读取配置文件。

1. 第一次优化:

为什么不读取一次,然后缓存起来呢?然后其它方法在调用 loadRoot() 时,就直接使用缓存中的就行了。但是遇到一个问题,InputStream 是不能被缓存,然后重复读取的,因为 InputStream 一旦被读取之后,其 pos 指针,等等都会发生变化,无法进行重复读取。所以只能将配置文件的内容读取处理,放入  byte[] 中缓存起来,然后配合 ByteArrayOutputStream,就可以重复读取 byte[] 缓存中的内容了。然后利用 ByteArrayOutputStream 来构造 InputStream 就达到了读取配置文件一次,然后重复构造 InputStream 进行重复读取,相关代码如下:

    // 为了避免原代码中频繁调用 loadRoot 去频繁读取 /mycat.dtd 和 /mycat.xml,所以将两个文件进行缓存,
// 注意这里并不会一直缓存在内存中,随着 LocalLoader 对象的回收,缓存占用的内存自然也会被回收。
private static byte[] xmlBuffer = null;
private static byte[] dtdBuffer = null;
private static ByteArrayOutputStream xmlBaos = null;
private static ByteArrayOutputStream dtdBaos = null; static {
InputStream input = ConfigFactory.class.getResourceAsStream("/mycat.dtd");
if(input != null){
dtdBuffer = new byte[1024 * 512];
dtdBaos = new ByteArrayOutputStream();
bufferFileStream(input, dtdBuffer, dtdBaos);
} input = ConfigFactory.class.getResourceAsStream("/mycat.xml");
if(input != null){
xmlBuffer = new byte[1024 * 512];
xmlBaos = new ByteArrayOutputStream();
bufferFileStream(input, xmlBuffer, xmlBaos);
}
}

bufferFileStream 方法:

    private static void bufferFileStream(InputStream input, byte[] buffer, ByteArrayOutputStream baos){
int len = -1;
try {
while ((len = input.read(buffer)) > -1 ) {
baos.write(buffer, 0, len);
}
baos.flush();
} catch (IOException e) {
e.printStackTrace();
logger.error(" bufferFileStream error: " + e.getMessage());
}
}

loadRoat 优化之后如下:

    private static Element loadRoot() {
Element root = null;
InputStream mycatXml = null;
InputStream mycatDtd = null; if(xmlBaos != null)
mycatXml = new ByteArrayInputStream(xmlBaos.toByteArray());
if(dtdBaos != null)
mycatDtd = new ByteArrayInputStream(dtdBaos.toByteArray()); try {
root = ConfigUtil.getDocument(mycatDtd, mycatXml).getDocumentElement();
} catch (ParserConfigurationException | SAXException | IOException e1) {
e1.printStackTrace();
logger.error("loadRoot error: " + e1.getMessage());
}finally{
if(mycatXml != null){
try { mycatXml.close(); } catch (IOException e) {}
}
if(mycatDtd != null){
try { mycatDtd.close(); } catch (IOException e) {}
}
} return root;
}

这样优化之后,即使有很多方法频繁调用 loadRoot() 方法,也不会重复读取配置文件了,而是使用 byte[] 内容,重复构造 InputStream 而已。

其实其原理,就是利用 byte[] 作为一个中间容器,对byte进行缓存,ByteArrayOutputStream 将 InputStream 读取的 byte 存放如 byte[]容器,然后利用 ByteArrayInputStream 从 byte[]容器中读取内容,构造 InputStream,只要 byte[] 这个缓存容器存在,就可以多次重复构造出 InputStream。 于是达到了读取一次配置文件,而重复构造出InputStream,避免了每构造一次InputStream,就读取一次配置文件的问题。

2. 第二次优化:

可能你会想到更好的方法,比如:

为什么我们不将 private static Element root = null; 作为类属性,缓存起来,这样就不需要重复打开和关闭配置文件了,修改如下:

public class LocalLoader implements ConfigLoader {
private static final Logger logger = LoggerFactory.getLogger("LocalLoader");
// ... ..
private static Element root = null; // 然后 loadRoot 方法改为:
private static Element loadRoot() {
InputStream dtd = null;
InputStream xml = null;
// Element root = null;
if(root == null){
try {
dtd = ConfigFactory.class.getResourceAsStream("/mycat.dtd");
xml = ConfigFactory.class.getResourceAsStream("/mycat.xml");
root = ConfigUtil.getDocument(dtd, xml).getDocumentElement();
} catch (ConfigException e) {
throw e;
} catch (Exception e) {
throw new ConfigException(e);
} finally {
if (dtd != null) {
try {
dtd.close();
} catch (IOException e) { }
}
if (xml != null) {
try {
xml.close();
} catch (IOException e) { }
}
}
} return root;
}

这样就不需要也不会重复 打开和关闭配置文件了。只要 root 属性没有被回收,那么 root 引入的 Document 对象也会在缓存中。这样显然比第一次优化要好很多,因为第一次优化,还是要从 byte[] 重复构造 InputStream, 然后重复 build 出 Document 对象。

3. 第三次优化

上面是将 private static Element root = null; 作为一个属性进行缓存,避免重复读取。那么我们干嘛不直接将 Document 对象作为一个属性,进行缓存呢。而且具有更好的语义,代码更好理解。代码如下:

public class LocalLoader implements ConfigLoader {
private static final Logger logger = LoggerFactory.getLogger("LocalLoader");
// ... ...
// 为了避免原代码中频繁调用 loadRoot 去频繁读取 /mycat.dtd 和 /mycat.xml,所以将 Document 进行缓存,
private static Document document = null; private static Element loadRoot() {
InputStream dtd = null;
InputStream xml = null;
if(document == null){
try {
dtd = ConfigFactory.class.getResourceAsStream("/mycat.dtd");
xml = ConfigFactory.class.getResourceAsStream("/mycat.xml");
document = ConfigUtil.getDocument(dtd, xml);
return document.getDocumentElement();
} catch (Exception e) {
logger.error(" loadRoot error: " + e.getMessage());
throw new ConfigException(e);
} finally {
if (dtd != null) {
try { dtd.close(); } catch (IOException e) { }
}
if (xml != null) {
try { xml.close(); } catch (IOException e) { }
}
}
}
return document.getDocumentElement();
}

这样才是比较合格的实现。anyway, 第一种优化,学习到了 ByteArrayOutputStream 和 ByteArrayInputStream 同 byte[] 配合使用的方法。

---------------------分割线------------------------------------

参考文章:http://blog.csdn.net/it_magician/article/details/9240727 原文如下:

有时候我们需要对同一个InputStream对象使用多次。比如,客户端从服务器获取数据 ,利用HttpURLConnection的getInputStream()方法获得Stream对象,这时既要把数据显示到前台(第一次读取),又想把数据写进文件缓存到本地(第二次读取)。

但第一次读取InputStream对象后,第二次再读取时可能已经到Stream的结尾了(EOFException)或者Stream已经close掉了。

而InputStream对象本身不能复制,因为它没有实现Cloneable接口。此时,可以先把InputStream转化成ByteArrayOutputStream,后面要使用InputStream对象时,再从ByteArrayOutputStream转化回来就好了。代码实现如下:

InputStream input =  httpconn.getInputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1 ) {
baos.write(buffer, 0, len);
}
baos.flush(); InputStream stream1 = new ByteArrayInputStream(baos.toByteArray()); //TODO:显示到前台 InputStream stream2 = new ByteArrayInputStream(baos.toByteArray()); //TODO:本地缓存

Java 利用 ByteArrayOutputStream 和 ByteArrayInputStream 避免重复读取配置文件的更多相关文章

  1. SpringBoot2 java配置方式 Configuration和PropertySource结合读取配置文件

    JdbcConfig.java Configuration是配置文件 PropertySource 引入配置文件 value读取配置文件内容 package cn.itcast.config; imp ...

  2. java 使用ByteArrayOutputStream和ByteArrayInputStream实现深拷贝

    首先介绍Java中的浅拷贝(浅克隆)和深拷贝(深克隆)的基本概念: 浅拷贝: 被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象.浅复制仅仅复制所考虑的对象,而 ...

  3. 【转】ByteArrayOutputStream和ByteArrayInputStream详解

    ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型别数组的缓冲区,然后利用ByteArrayOutputStream和ByteArrayInputStream的 ...

  4. InputStream为什么不能被重复读取?

    最近上传阿里云的时候同一个文件上传两个服务地址,第一个文件读取以后第二个再去读取就拿不到了.代码如下: //内网上传OSS获取key值 String ossKey = OSSClientUtil.ge ...

  5. Java IO --ByteArrayOutputStream (六)***

    Java提供了很丰富的io接口,已经可以满足我们大部分读取数据的需求,这个在C读取数据需要自己定义缓冲区数组大小,而且要小心翼翼的防止缓冲区溢出的情况相当不同.一般情况下我们读取的数据都是直接读取成为 ...

  6. Java基础-IO流对象之内存操作流(ByteArrayOutputStream与ByteArrayInputStream)

    Java基础-IO流对象之内存操作流(ByteArrayOutputStream与ByteArrayInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.内存 ...

  7. 利用java反射机制 读取配置文件 实现动态类载入以及动态类型转换

    作者:54dabang 在spring的学习过程之中,我们能够看出通过配置文件来动态管理bean对象的优点(松耦合 能够让零散部分组成一个总体,而这些总体并不在意之间彼此的细节,从而达到了真正的物理上 ...

  8. 【java】内存流:java.io.ByteArrayInputStream、java.io.ByteArrayOutputStream、java.io.CharArrayReader、java.io.CharArrayWriter

    package 内存流; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java. ...

  9. 【转载】 java利用snmp4j包来读取snmp协议数据(Manager端)

    https://www.cnblogs.com/xdp-gacl/p/4187089.html http://doc.okbase.net/yuanfy008/archive/265663.html ...

随机推荐

  1. 由select * from table where 1=1中的1=1说开数据库

    众多网站都有select * from table where 1=1此类语句的介绍,并且,针对该类语句,讲得实在是让人越看越迷茫(一个抄袭一个的,简直不像话),不知道是在说什么,导致很多新手不得要领 ...

  2. [mysql] 查看mysql执行时间

    mysql的 profiling不是默认打开的 查看profiling是否找开 mysql> show variables like "%pro%"; +---------- ...

  3. SSH中的jar包讲解(1)

    我们在搭建SSH框架的时候,需要引入各自的一些jar包,相信很多初学者跟我一样,搜个资料,照搬过来(当然版本还得对应),至于为什么要引入这些个jar包,引入它们的作用是啥子,一头雾水,今天我就来跟这些 ...

  4. ANDROID 应用退出

    在android中finish()和system(0)都只能退出单个activity.杀进程等的等方式都不行~~~解决问题: 在针对 多activity中退出整个程序,例如从A->B->C ...

  5. 高性能 Windows Socket 组件 HP-Socket v2.3.1-beta-2 发布

    HP-Socket 是一套通用的高性能 Windows Socket 组件包,包含服务端组件(IOCP 模型)和客户端组件(Event Select 模型),广泛适用于 Windows 平台的 TCP ...

  6. 为友盟消息推送开发的PHP SDK(composer版):可以按省发Android push

    一直以来APP希望按省市县推送Android push,只能自己分析用户经纬度,打tag发送. 现在终于有服务商提供了. 友盟消息推送 可以“按省推送”,很方便. 我为友盟做了PHP SDK(comp ...

  7. Autodesk的照片建模云服务—Autodesk ReCap 360 photo

    现实捕捉技术方兴未艾,简单的讲现实捕捉技术就是把现实中的现状信息数字化到计算机中以便做进一步的处理.对于不同的应用目的会有不同的捕捉设备,工程或传媒娱乐行业中经常用到的肯定就是三维模型了.那如何得到三 ...

  8. 国内最全最详细的hadoop2.2.0集群的MapReduce的最简单配置

    简介 hadoop2的中的MapReduce不再是hadoop1中的结构已经没有了JobTracker,而是分解成ResourceManager和ApplicationMaster.这次大变革被称为M ...

  9. Win7重装系统遇到的问题以及MysQL的问题解决

    连续三天因为系统的错误,android方面的软件一直不能正确运行.而且每次开机的时候QQ 微信等聊天工具也出现损坏.虽然重新下载一个可以保证在电脑不管的情况下正常的运行.可是作为玩电脑时间不长的我来说 ...

  10. NSTimer 定时器总结

    一.初始化方法:有五种初始化方法,分别是 + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation ...