Marshalling在国内现在用的人比较少了,1.3.0版本支持的是Netty5.0的版本,随着Netty5.0被废弃,1.3.0也就没人用了,也不兼容主流的Netty4.X,随后的Marshalling版本也不断的升级,目前为止2.X版本了,但是国内还是没啥人用了,我猜测的原因是现在的开发信息传输跨平台已经成为了刚需,Marshalling本身性能,1.3.0版本在Netty5.0上非常易用,但是Marshalling不支持跨平台传输(不清楚最新的支不支持),再加上Google的Protobuf性能和Marshalling差不多,虽然不像前者在Netty中那么易用,但是我跨平台啊,而且随着发展,国内用Protobuf的人越来越多,当然还有其它类似优秀的序列化框架,例如基于Protobuf的Kyro,在分布式平台上用得比较多,还有MessagePack框架等。
package marshalling;
import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
/**
* @description JBoss Marshalling编解码工厂类,版本1.3.0.CR9
*/
public final class MarshallingCodeCFactory {
//创建解码器
public static MarshallingDecoder buildMarshallingDecoder(){
//首先通过Marshalling工具类的getProvidedMarshallerFactory静态方法获取MarshallerFactory实例
//参数“serial”表示创建的是Java序列化工厂对象,它由jboss-marshalling-serial-1.3.0.CR9.jar提供。
final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
//创建了MarshallingConfiguration对象并设置版本号为5
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setVersion(5);
//然后根据MarshallerFactory和MarshallingConfiguration创建UnmarshallerProvider实例
UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
//最后通过构造函数创建Netty的MarshallingDecoder对象,两个参数分别是UnmarshallerProvider和单个消息序列化后的最大长度。
MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);
return decoder;
}
//创建编码器
public static MarshallingEncoder buildMarshallingEncoder(){
final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setVersion(5);
//创建MarshallerProvider对象,它用于创建Netty提供的MarshallingEncoder实例
MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);
//MarshallingEncoder用于将实现序列化接口的POJO对象序列化为二进制数组。
MarshallingEncoder encoder = new MarshallingEncoder(provider);
return encoder;
}
}
在服务器和客户端中添加一下代码就可以了,非常简单易用:
sc.pipeline().addLast(
MarshallingCodeCFactory.buildMarshallingDecoder(),
MarshallingCodeCFactory.buildMarshallingEncoder()
);
代码来源,marshalling百度百科