Netty权威指南(三)Netty入门应用

回顾NIO开发步骤

  1. 创建ServerSocketChannel,配置为非阻塞模式。
  2. 绑定监听,配置TCP参数,例如backlog大小。
  3. 创建一个独立的I/O线程,用于轮询多路复用器Selector
  4. 创建Selector,将之前创建的ServerSocketChannel注册到Selector上,监听SelectionKey.ACCEPT
  5. 启动IO线程,在循环体中执行Selector.select()方法。轮询就绪的Channel
  6. 当轮询到了处于就绪状态的Channel时,需要对其进行判断,如果是OP_ACCEPT状态,说明是新的客户端接入,则调用ServerSocketChannel.accept()方法接收新的客户端。
  7. 设置新接入的客户端链路SocketChannel为非阻塞模式,配置其他的一些TCP参数。
  8. SocketChannel注册到Selector上,监听OP_READ操作位。
  9. 如果轮询的ChannelOP_READ,则说明SocketChannel中有询的就绪的数据包。
  10. 如果轮询的ChannelOP_WRITE,说明还有数据没有发送完成,需要继续发送。

一个简单的NIO服务端程序,如果我们直接使用JDK的NIO类库进行开发,竟然需要经过繁琐的十多步操作才能完成最基本的消息读取和发送,这也是我们选择Netty框架的原因了。下面我们看看Netty是如何轻松搞定服务端开发的。

一、依赖

使用的是netty5版本的依赖,与4版本的ChannelHandlerAdapter类稍微有些区别。

 <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha2</version>
        </dependency>

二、Netty TimeServer

package com.lsh.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author :LiuShihao
 * @date :Created in 2021/3/8 12:09 下午
 * @desc :Netty服务端开发
 */
public class TimeServer {

    public void bind(int port) throws Exception{
        /**
         * 配置服务端的NIO线程组 创建两个NioEventLoopGroup实例 ,
         * NioEventLoopGroup是个线程组 它包含了一组NIO线程,专门用于网络事件的处理,实际上它们就是Reactor线程组
         * 这里创建两个的原因是一个用于服务端接收客户端的连接,另一个就是用于进行SocketChannel的网络读写,
         */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            /**
             *ServerBootstrap 是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
             * 调用ServerBootstrap的group方法:
             * 将两个NIO线程组当做入参传递到ServerBootstrap中,
             * 1.channel设置的为NIOServerSocketChannel,功能对应于NIO的ServerSocketChannel
             * 2.配置NIOServerSocketChannel的TCP参数
             * 3.绑定IO事件的处理类ChildChannelHandler,作用主要是类似于Reactor模式中的Handler类,主要用于
             * 处理网络IO事件例如记录日志,对消息进行编解码等
             *
             */
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChildChannelHandler());
            /**
             * 绑定端口,同步等待成功
             */
            ChannelFuture sync = b.bind(port).sync();
            //等待服务端监听端口关闭
            sync.channel().closeFuture().sync();

        }finally {
            //优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(new TimeServerHandler());

        }

    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new TimeServer().bind(port);

    }


}

总结:

  1. 创建两个NioEventLoopGroup实例:NIOEventLoopGroup是一个线程组,它包含了一组NIO线程,专门用于网络事件的处理,实际上他们就是Reactor线程组,这里创建两个的原因是一个用于服务端接收客户端的连接,另一个用于进行SocketChannel的网络读写。

  2. 创建的ServerBootstarp对象:它是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度。

  3. ServerBootstrap的group方法:将两个NIO线程组当作入参传递到ServerBootstrap中。

  4. 接着设置创建的Channel为NioServerSocketChannel,就相当于Java 的NIO类库中的ServerSocketChannel。然后配置NioServerSocketChannel的TCP参数,此处将它的backlog设置为1024,最后绑定I/O事件的处理类为ChildChannelHandler,它的作用类型于Reactor模式中的Handler类,主要用于处理网络I/O事件,例如记录日志、对消息进行编解码等。

  5. 服务端启动辅助类配置完成后,调用它的bind方法绑定监听端口,随后,调用它的同步阻塞方法sync等待绑定操作完成。完成之后会返回一个ChannelFuture,它的功能类似于JDK的java.util.concurrent.Future,主要用于异步操作的通知回调。

  6. 使用sync()方法进行阻塞,等待服务端链路关闭之后main函数才退出。

  7. NIO线程组的shutdownGracefully 进行优雅退出,它会释放跟shutdownGracefully相关联的资源。

三、Netty TimeServerHandler

package com.lsh.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @author :LiuShihao
 * @date :Created in 2021/3/8 12:39 下午
 * @desc :
 */
public class TimeServerHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String( req,"UTF-8");
        System.out.println("The time server receive order :"+body);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws  Exception{
        ctx.flush();

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }


}

总结:
TimeServerHandler 继承自 ChannelHandlerAdapter ,它用于对网络事件进行读写操作。通常我们只需要关注channelReadexceptionCaught方法。

  1. 类行转换:将msg转换成Netty的ByteBuf 对象,ByteBuf类似于JDK的java.nio.ByteBuffer 对象,不过它提供了更加强大和灵活的功能。通过ByteBufreadableBytes方法可以获取缓冲区可读的字节数,根据可读的字节数创建byte数组,通过ByteBufreadBytes方法将缓冲区中的字节数组复制到新建的byte数组中,最后通过new String 构造函数 获取请求消息。这时对请求消息进行判断,如果是“QUERY TIME OREER”则创建应答消息,通过ChannelHandlerContextwrite方法异步发送应答消息给客户端。
  2. ChannelHanContext的flush()方法:它的作用是将消息发送队列中的消息写入到SocketChannel 中发送给对方。从性能角度考虑,为了防止频繁的唤醒Selector进行消息发送,Netty的write方法并不直接将消息写入SocketChannel中,调用writer方法只是把待发送消息放到发送缓冲数组中,在通过flash()方法,将发送缓冲区中的消息全部写到SocketChannel中。
  3. 当发生异常时:关闭ChannelHandlerContext,释放和ChannelHandlerContext相关联的句柄等资源。

Netty权威指南(二)NIO模型
通过对代码统计分析可以看出,不到30行的业务逻辑代码,即完成了NIO服务端的开发,相比于传统基于JDK NIO
原生类库的服务端,代码量大大减少,开发难度也降低了很多。

四、Netty TimeClient

package com.lsh.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author :LiuShihao
 * @date :Created in 2021/3/17 12:09 下午
 * @desc :基于Netty的TimeClient
 */
public class TimeClient {

    public void connect (int port,String host) throws Exception{
        //配置客户端NIO线程组
        NioEventLoopGroup group = new NioEventLoopGroup();

        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new TimeClientHandler());
                        }
                    });
            //发起异步连接操作

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

            //等待客户端链路关闭
            f.channel().closeFuture().sync();

        }finally {

            //优雅退出 释放NIO线程组

            group.shutdownGracefully();

        }

    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new TimeClient().connect(port,"127.0.0.1");
    }
}

总结:

  1. 首先创建客户端处理I/O读写的NioEventLoopGroup线程组。
  2. 然后继续创建客户端辅助启动类Bootstrap,随后需要对其进行配置。
  3. 与服务端不同的是:它的Channel需要设置为NioSocketChannel
  4. 然后为其添加Handler,此处为了简单直接使用了匿名内部类,实现initChannel()方法,其作用是当创建NioSocketChannel成功之后,在进行初始化时,将它的ChannelHandler设置到ChannelPipeline中,用于处理网络IO事件。
  5. 客户端启动辅助类完成之后,调用connect方法发起异步连接,然后调用同步方法等待连接成功。
  6. 最后,当客户端连关闭之后,客户端主函数退出退出之前释放NIO线程组的资源。

五、Netty TimeClientHandler

package com.lsh.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author :LiuShihao
 * @date :Created in 2021/3/17 12:13 下午
 * @desc :
 */
public class TimeClientHandler extends ChannelHandlerAdapter {

    private final ByteBuf firstMessage;

    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx){
        ctx.writeAndFlush(firstMessage);
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception{
        ByteBuf buf = (ByteBuf) msg;

        byte[] req = new byte[buf.readableBytes()];

        buf.readBytes(req);

        String body = new String(req, "UTF-8");

        System.out.println("Now is :"+body);



    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}

总结:
这里关注三个方法:channelActive、channelRead、exceptionCaught。

  1. 当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用channelActive方法,发送查询时间的指令给服务器,调用ChannelHandlerContext的writeAndFlush方法将请求消息发送给服务端。
  2. 当服务端返回应答消息时,channelRead方法被调用,从Netty的ByteBuf中读取并打印应答消息。
  3. 当发生异常时,打印异常日志,释放客户端资源。

六、总结

经过调试,运行结果正确,可以发现,通过Netty开发的NIO服务端和客户端非常简单,短短几十行代码就能完成之前NIO程序需要几百行才能完成的功能,基于Netty的应用开发不但API使用简单、开发模式固定,而且扩展性和定制性非常好,后面,我们会通过更多应用来介绍Netty的强大功能。
需要指出的是,本程序依然没有考虑读半包的处理,对于功能演示或者测试,上述程序并没有问题,但是稍加改造进行性能和压力测试,他就不能正确的工作了。在下一章我们会给出能够正确处理半包消息的应用实例。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liu_Shihao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值