JBoss Marshalling是一个Java对象序列化包,兼容Java原生的序列化机制,对Java原生序列化机制做了优化,使其在性能上有很大提升。在保持跟java.io.Serializable接口兼容的同时增加了一些可调的参数和附加特性,这些参数和附加特性,可通过工厂类进行配置,对原生Java序列化是一个很好的替代。
代码如下:
package ares.remoting.framework.serialization.serializer.impl;
import ares.remoting.framework.serialization.serializer.ISerializer;
import org.jboss.marshalling.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author fuss created on 18/7/23.
* @version $Id$
*/
public class MarshallingSerializer implements ISerializer {
final static MarshallingConfiguration configuration = new MarshallingConfiguration();
//获取序列化工厂对象,参数serial标识创建的是java序列化工厂对象
final static MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
static {
configuration.setVersion(5);
}
public byte[] serialize(Object obj) {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
final Marshaller marshaller = marshallerFactory.createMarshaller(configuration);
marshaller.start(Marshalling.createByteOutput(byteArrayOutputStream));
marshaller.writeObject(obj);
marshaller.finish();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toByteArray();
}
public <T> T deserialize(byte[] data, Class<T> clazz) {
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
final Unmarshaller unmarshaller = marshallerFactory.createUnmarshaller(configuration);
unmarshaller.start(Marshalling.createByteInput(byteArrayInputStream));
Object object = unmarshaller.readObject();
unmarshaller.finish();
return (T) object;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
maven 依赖配置如下:
<!-- marshalling -->
<dependency>
<groupId>org.jboss.marshalling</groupId>
<artifactId>jboss-marshalling-serial</artifactId>
<version>2.0.0.Beta2</version>
</dependency>