【MINA】序列化和反序列化我们要考虑的问题

 

概念

序列化:将java对象转换为字节序列的过程叫做序列化

 

反序列化:将字节对象转换为java对象的过程叫做反序列化

解决的问题

1.序列化时间

2.反序列化时间

3.bytes大小

4.操作方便  支持的数据类型和应用传输数据的格式是否恰当

 

例举几种方式序列化的方式:有一篇很好的文章http://www.iteye.com/topic/1128868

 

说白了就是只有编码后的包小,才能传的快,只有解码的时候效率高,才能使协议处理的效率高

选用什么的编解码协议,我觉得要本着易用,效率高为原则,

 

比如protobuff,优点:字节数很小,适合网络传输节省io,跨语言 。缺点:需要依赖于工具生成代码,不易用

编码可以用jprotobuff这个中间件,很方便,可解码就悲剧了,很麻烦,另外对于复杂的数据类型,也不好处理

 

java 自带的

优点:java原生支持,不需要提供第三方的类库,使用比较简单。缺点:无法跨语言,字节数占用比较大,某些情况下对于对象属性的变化比较敏感。

 

json

Json的优点:明文结构一目了然,可以跨语言,属性的增加减少对解析端影响较小。缺点:字节数过多,依赖于不同的第三方类库。

 

amf3 比较适合大数据传输,另外压缩比很高,适用于slg类型的后台计算,前台展示的游戏,另外Object和array于java的互转比较省事

 

列出我项目用到的java和amf3解码的代码

    

      public void amf3Decode(ProtocolDecoderOutput out, byte[] bytes,
			boolean compressed) throws Exception {

		int len = bytes.length;

		ByteArrayInputStream bios = new ByteArrayInputStream(bytes, 0, len);

		Amf3Input amf3in = null;
		try {
			amf3in = new Amf3Input(context);
			if (compressed) {
				amf3in.setInputStream(new GZIPInputStream(bios));
			} else {
				amf3in.setInputStream(bios);
			}
			Object message = amf3in.readObject();
			if (message != null) {
				out.write(message);
			}

		} finally {
			if (amf3in != null) {
				amf3in.close();
			}
		}

	}

	public void javaDecode(ProtocolDecoderOutput out, byte[] bytes,
			boolean compressed) throws Exception {
		int len = bytes.length;

		ByteArrayInputStream bios = new ByteArrayInputStream(bytes, 0, len);

		ObjectInputStream ois = null;

		try {
			if (compressed) {
				ois = new ObjectInputStream(new InflaterInputStream(bios));
			} else {
				ois = new ObjectInputStream(bios);
			}
			Object message = ois.readObject();
			if (message != null) {
				out.write(message);
			}

		} finally {
			if (ois != null) {
				ois.close();
			}
		}

		// in.close();

	}

  

 

  列出我项目中java和amf3编码的代码

     

    protected void getAmf3Bytes(IoBuffer buffer, Object message)
			throws Exception {
		Amf3Output amf3out = null;
		try {
			amf3out = new Amf3Output(context);
			amf3out.setOutputStream(new IoBufferOutputStream(buffer));
			amf3out.writeObject(message);
			amf3out.flush();
		} finally {
			if (amf3out != null) {
				amf3out.close();
			}
		}
	}

	protected void getJavaBytes(IoBuffer buffer, Object message)
			throws Exception {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new IoBufferOutputStream(buffer));
			oos.writeObject(message);
			oos.flush();
		} finally {
			if (oos != null) {
				oos.close();
			}
		}
	}

  

 

posted on 2015-08-10 14:40  dagangzi  阅读(415)  评论(0编辑  收藏  举报