Netty学习之路(九)-JBoss Marshalling编解码

JBoss Marshalling 是一个Java对象序列化包,对JDK默认的序列化框架进行了优化,但又保持跟java.io.Serializable接口的兼容,同时增加了一些可调的参数和附加的特性。

Marshalling开发环境准备

下载相关的Marshalling类库:地址,将该jar导入项目即可。

创建Marshalling编解码器

通过创建MarshallingCodeCFactory工厂类来创建MarshallingDecoder解码器与MarshallingEncoder编码器。

package com.ph.Netty;

import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

/**
 * Create by PH on 2018/11/10
 */
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;
    }

}

传输的POJO类

package com.ph.Netty;

/**
 * Create by PH on 2018/11/10
 */
public class BookInfo implements java.io.Serializable {

    private int id;
    private String name;
    private String type;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override public String toString() {
        return "{" + "id=" + id + ", name=" + name + ", type='" + type + '\'' + '}';
    }

}

Netty的Marshalling服务端开发

package com.ph.Netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Create by PH on 2018/11/10
 */
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线程组
        //bossGroup仅接收客户端连接,不做复杂的逻辑处理,为了尽可能减少资源的占用,取值越小越好
        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 {
        BookInfo bookInfo = (BookInfo)msg;
        System.out.println("Server receive: " + bookInfo.toString());
        BookInfo bookInfo1 = new BookInfo();
        bookInfo1.setId(bookInfo.getId());
        bookInfo1.setName("Server Netty Marshalling");
        bookInfo1.setType("book order succeed");
        ctx.writeAndFlush(bookInfo1);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将消息发送队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //当发生异常时释放资源
        ctx.close();
    }
}

Netty的Mashalling客户端开发

package com.ph.Netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Create by PH on 2018/11/10
 */
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++) {
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(i);
            bookInfo.setName("Client Netty Marshalling");
            bookInfo.setType("buy book");
            ctx.write(bookInfo);
        }
        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();
    }
}

运行结果

服务端:
在这里插入图片描述
客户端:
在这里插入图片描述
通过运行结果可看出并没有发生粘包现象,说明Marshalling的编解码器支持半包和粘包的处理,对于普通的开发者来说,只需要将Marshalling编码器和解码器加入到ChannelPipline中,就能实现对Marshalling序列化的支持。

猜你喜欢

转载自blog.csdn.net/PH15045125/article/details/83930307