Netty入門

分母為零發表於2018-10-14

Netty是一個非同步的事件驅動網路框架,使用Netty可以研發高效能的私有協議,將業務邏輯和網路進行解耦,通過Netty我們可以實現一些常用的協議,如HTTP。

基本概念

Channel

Channel是NIO的基礎,它代表一個連線,通過這個連結可以進行IO操作,例如讀和寫。

Future

在Netty的Channel中的每一個IO操作都是非阻塞的。 這就意味著每一個操作都是立刻返回結果的。在Java標準庫中有Future介面,但是我們使用Future的時候只能詢問這個操作是否執行完成,或者阻塞當前的執行緒直到結果完成,這不是Netty想要的。

Netty實現了自己的ChannelFuture介面,我們可以傳遞一個回撥到ChannelFuture,當操作完成的時候才會執行回撥。

Events 和 Handlers

Netty使用的是事件驅動的應用設計,因此Handler處理的資料流,在管道中是鏈式的事件。事件和Handler可以被 輸入 和 輸出的資料流進行關聯。

輸入(Inbound)事件可以如下:

  • Channel啟用和滅活
  • 讀操作事件
  • 異常事件
  • 使用者事件

輸出(Outbound)事件比較簡單,一般是開啟和關閉連線,寫入和重新整理資料。

Encoder 和 Decoder

因為我們要處理網路協議,需要運算元據的序列化和反序列化。

程式碼

來個實際的案例:

  1. 新建專案,新增maven依賴
    <properties>
        <netty-all.version>4.1.6.Final</netty-all.version>
    </properties>


    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>${netty-all.version}</version>
        </dependency>
    </dependencies>
複製程式碼
  1. 建立資料的pojo
public class RequestData {
    private int intValue;
    private String stringValue;

    // getter 和 setter
    // toString方法
}

public class ResponseData {
    private int intValue;
    
    // getter 和 setter
    // toString方法    
}

複製程式碼
  1. 建立Encoder和Decoder
public class RequestDataEncoder extends MessageToByteEncoder<RequestData> {

    private final Charset charset = Charset.forName("UTF-8");

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RequestData msg, ByteBuf out) throws Exception {
        out.writeInt(msg.getIntValue());
        out.writeInt(msg.getStringValue().length());
        out.writeCharSequence(msg.getStringValue(), charset);
    }
}

public class ResponseDataDecoder extends ReplayingDecoder<ResponseData> {

    @Override
    protected void decode(ChannelHandlerContext ctx,
                          ByteBuf in, List<Object> out) throws Exception {

        ResponseData data = new ResponseData();
        data.setIntValue(in.readInt());
        out.add(data);
    }
}


public class RequestDecoder extends ReplayingDecoder<RequestData> {

    private final Charset charset = Charset.forName("UTF-8");

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

            RequestData data = new RequestData();
            data.setIntValue(in.readInt());
            int strLen = in.readInt();
            data.setStringValue(
                    in.readCharSequence(strLen, charset).toString());
            out.add(data);
    }
}


public class ResponseDataEncoder extends MessageToByteEncoder<ResponseData> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ResponseData msg, ByteBuf out) throws Exception {
        out.writeInt(msg.getIntValue());
    }
}

複製程式碼
  1. 建立請求的處理器
public class ProcessingHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RequestData requestData = (RequestData) msg;
        ResponseData responseData = new ResponseData();
        responseData.setIntValue(requestData.getIntValue() * 2);
        ChannelFuture future = ctx.writeAndFlush(responseData);
        future.addListener(ChannelFutureListener.CLOSE);
        System.out.println(requestData);
    }
}


public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx)
            throws Exception {

        RequestData msg = new RequestData();
        msg.setIntValue(123);
        msg.setStringValue(
                "正常工作");
        ChannelFuture future = ctx.writeAndFlush(msg);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        System.out.println((ResponseData)msg);
        ctx.close();
    }
}
複製程式碼
  1. 建立服務端應用
public class NettyServer {
    private int port;
    

    public NettyServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {

        int port = args.length > 0
                ? Integer.parseInt(args[0]) : 9003;

        new NettyServer(port).run();
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new RequestDecoder(),
                                    new ResponseDataEncoder(),
                                    new ProcessingHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

複製程式碼
  1. 建立客戶端應用
public class NettyClient {
    public static void main(String[] args) throws Exception {

        String host = "127.0.0.1";
        int port = 9003;
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new RequestDataEncoder(),
                                    new ResponseDataDecoder(), new ClientHandler());
                        }
                    });

            ChannelFuture f = b.connect(host, port).sync();

            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
複製程式碼
  1. 執行服務端和客戶端

image

image

可見正常工作

最後

這裡我們只是對Netty進行簡單的介紹,介紹了它一些基本的概念,然後演示了一個例子。後續我們會對Netty進行更深入的研究

參考

相關文章