JBoss Marshalling是一个Java对象序列化包,对JDK默认的序列化框架进行了优化,但又保持了跟java的Serializable接口的兼容,同时增加了一些可调的参数和附加特性。
1.Marshalling 工厂类
Marshalling的可调参数和附加特性通过工厂类进行配置。
使用工厂类定义Marshalling编解码器。
public final class MarshallingCodeCFactory {
/**
* JBoss Marshalling 解码器
* @return
*/
public static MarshallingDecoder buildMarshallingDecoder() {
//参数“serial”表示创建的是Java序列化工厂对象
final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setVersion(5);
UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
//1024表示单个消息序列化后的最大长度
MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);
return decoder;
}
/**
* JBoss Marshalling 编码器
* @return
*/
public static MarshallingEncoder buildMarshallingEncoder() {
final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
final MarshallingConfiguration configuration = new MarshallingConfiguration();
configuration.setVersion(5);
MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);
MarshallingEncoder encoder = new MarshallingEncoder(provider);
return encoder;
}
}
2.传输的POJO类
@Data
public class User implements java.io.Serializable {
private String userName;
private String password;
}
3.Netty的Marshalling服务端开发
public class NettyServer {
public static void main(String[] args) throws Exception {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//采用默认值
}
}
new NettyServer().bind(port);
}
public void bind(int port) throws Exception{
//NioEventLoopGroup是一个线程组,包含了一组NIO线程,专门用于网络事件的处理,实际上他们就是Reactor线程组
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//用于进行SocketChannel的网络读写
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
ServerBootstrap b = new ServerBootstrap();
//配置NIO服务端
b.group(bossGroup, workerGroup)
//指定使用NioServerSocketChannel产生一个Channel用来接收连接,他的功能对应于JDK
// NIO类库中的ServerSocketChannel类。
.channel(NioServerSocketChannel.class)
//BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,
// 用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,
// Java将使用默认值50。
.option(ChannelOption.SO_BACKLOG, 1024)
//绑定I/O事件处理类,作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
arg0.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
arg0.pipeline().addLast(new ServerHandler());
}
});
//绑定端口,同步等待绑定操作完成,完成后返回一个ChannelFuture,用于异步操作的通知回调
ChannelFuture f = b.bind(port).sync();
//等待服务端监听端口关闭之后才退出main函数
f.channel().closeFuture().sync();
} finally {
//退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
/**
* ChannelInboundHandlerAdapter实现自ChannelInboundHandler
* ChannelInboundHandler提供了不同的事件处理方法你可以重写
*/
class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* 接受客户端发送的消息
* @param ctx
* @param msg
* @throws Exception
*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println((User)msg.getUserName());
System.out.println((User)msg.getPassword());
User user1 = new User();
user1.setUserName((User)msg.getUserName());
user1.setPassword("*****");
ctx.channel().writeAndFlush(user1);
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将消息发送队列中的消息写入到SocketChannel中发送给对方
ctx.flush();
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//当发生异常时释放资源
ctx.close();
}
}
4.Netty的Marshalling客户端开发
public class NettyClient {
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
//采用默认值
}
}
new NettyClient().connect(port, "127.0.0.1", 10);
}
public void connect(int port, String host, int sendNumber) throws Exception{
//配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
ch.pipeline().addLast(new ClientHandler(sendNumber));
}
});
//发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
//等待客户端链路关闭
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
class ClientHandler extends ChannelInboundHandlerAdapter {
private int sendNumber;
public ClientHandler(int sendNumber) {
this.sendNumber = sendNumber;
}
/**
* 当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用此方法
* @param ctx
*/
public void channelActive(ChannelHandlerContext ctx) {
for (int i=0;i<sendNumber;i++) {
User user = new User();
user.setUserName("mazi");
user.setPassword("mazi")
ctx.write(user);
}
ctx.flush();
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
System.out.println("Client receive :" + msg);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}
注:与google的Protobuf不同的是,Netty的Marshalling 编解码支持半包和粘包的处理,不需要额外再添加半包/粘包的处理。