netty组件解析

Netty学习

1、 BIO/NIO/AIO

2、netty组件解析

3、Netty编解码&粘包拆包&心跳检测与重连&零拷贝

      Netty心跳检测代码实例

NIO的类库和Api繁杂,使用麻烦:需要熟练掌握Selector、ServerSocketChannel、SocketChannel和ByteBuffer等。

开发工作量和难度较大,有以下问题:

    客户端面临断连重连、网络闪断、心跳处理、半包读写、网络拥塞和异常流的处理等。

Netty对JDK自带的NIO的Api进行了良好的封装,解决了上述的问题。且Netty拥有高性能、更高吞吐量,延迟更低,减少资源消耗,最小化不必要的内存复制等优点。

Netty基本使用4.X,5.x版本已经弃用,Netty4.x需要JDK1.6以上版本支持。

Netty使用场景

1、互联网行业:在分布式系统中,各个节点之间需要远程服务调用,高性能的RPC框架必不可少,Netty作为异步高性能的通信框架,往往作为基础通信组件倍这些RPC框架使用。典型的应用有:阿里的分布式框架Dubbo的RPC框架使用Dibbo协议进行节点通信,Dubbo协议默认使用Netty作为基础通信组件,用于实现各进程节点之间的内部通信。Rocketmq底层也是应用Netty作为基础通信组件。

2、游戏行业:无论是手游服务端还是大型的网络游戏,Java语言得到了越来越广泛的应用。Netty作为高性能的基础通信组件,它本身提供了TCP/UDP和HTTP协议栈。

3、大数据领域:经典的Hadoop的高性能通信和序列化组件AVRO的RPC框架,默认采用Netty进行跨节点通信,它的Netty Server基于Netty框架二次封装实现。

Netty线程模型

netty组件解析_第1张图片

解释如下:

1、Netty抽象出两组线程池BossGroup和WorkerGroup,BossGroup专门负责接收客户端的连接,WorkerGroup专门负责网络读写;

2、BossGroup和WorkerGroup类型都是NioEventGroup;

3、NioEventLoopGroup相当于一个事件循环线程组,这个组中含有多个事件循环线程,每一个事件循环线程是NioEventLoop;

4、每个NioEventLoop都有一个Selector,用于监听注册在其上的socketChannel的网络通讯;

5、每个Boss NioEventLoop线程内部循环执行的步骤如下:

  • 处理accept事件,与client建立连接,生成NioSocketChannel
  • 将NioSocketChannel注册到某个work NioEventLoop上的Selector;
  • 处理任务队列的任务,即runAllTasks。

6、每个worker NioEventLoop线程循环执行的步骤如下:

  • 轮询注册到自己selector上的所有NioSocketChannel的read,write事件;
  • 处理I/O事件,即read、write事件,在对应的NioSocketChannel上处理业务;
  • runAllTasks处理任务队列TaskQueue的任务,一些耗时的业务处理一般可以放入TaskQueue中慢慢处理,这样不影响数据在pipeline中的流动处理;

7、每个work NioEventLoop处理NioSocketChannel业务时,会使用pipeline(管道),管道中维护了很多handler处理器用来处理channel中的数据。

Netty模块组件

【Bootstrap、ServerBootstrap】

Bootstrap意思是引导,一个Netty应用通常由一个Bootstrap开始,主要作用是配置整个Netty程序,串联各个组件,Netty中的Bootstrap类是客户端程序的启动引导类,ServerBootstrap是服务端的启动引导类。

【Future、ChannelFuture】

在Netty中所有的IO操作都是异步的,不能立即得知消息是否被正确处理。但是可以过一会等它执行完成或者直接注册一个监听,具体的实现是通过Future和ChannelFuture,他们可以注册一个监听,当操作执行成功或者失败时监听会自动触发注册的监听事件。

【Channel】

Netty网络通信的组件,能够用于执行网络I/O操作。Channel为用户提供:

1、当前网络连接的通道的状态(例如是否打开?是否已连接?);

2、网络连接的配置参数(例如接收缓冲区大小);

3、提供异步的网络I/O操作(如建立连接,读写,绑定端口),异步调用意味着任何I/O调用都立即返回,并且不保证在调用结束时所请求的I/O操作已完成;

4、调用立即返回一个ChannelFuture实例,通过注册监听器到ChannelFuture上,可以I/O操作成功、失败或取消时回调通知调用方;

5、支持关联I/O操作与对应的处理程序。

不同协议、不同的阻塞类型的连接都有不同的channel类型与之对应。

下面是一些常用的channel类型:

NioSocketChannel:异步的客户端TCP socket连接;
NioServerSocketChannel:异步的服务端TCP socket连接;
NioDatagramChannel::异步的UDP连接;
NioSctpChannel::异步的客户端Scpt连接;
NioSctpServerChannel::异步的Scpt服务端连接,这些通道涵盖了UDP和TCP网络IO以及文件IO。

【Selector】

Netty基于Selector实现I/O多路复用,通过Selector一个线程可以监听多个连接的Channel事件。

当向一个Selector中注册Channel后,Selector内部的机制就可以自动不断的查询(select)这些注册的Channel是否有已就绪的I/O事件(例如可读,可写,网络连接完成等),这些程序就可以很简单的使用一个线程搞笑地管理多个Channel。

【NioEventLoop】

NioEventLoop中维护了一个线程和任务队列,支持异步提交执行任务,线程启动时会调用NioEventLoop的run方法,执行I/O任务和非I/O任务;

I/O任务,即selectionKey中ready的事件,如accept、connect、read、write等,由processSelectedKeys方法触发。

非I/O任务,添加到taskQueue中的任务,如register()、bind()等任务,有runAllTasks方法触发。

【NioEventLoopGroup】

主要管理eventloop的生命周期,可以理解为一个线程池,内部维护了一组线程,每个线程(NioEventLoop)负责处理多个Channel上的事件,而一个Channel只对应一个线程。

【ChannelHandler】

ChannelHandler是一个接口,处理I/O事件或拦截I/O操作,并将其转发到其ChannelPipeline(业务处理链)中的下一个处理程序。

ChannelHandler本身没有提供很多方法,因为这个接口有许多的方法需要实现,方便使用期间,可以继承它的子类:

ChannelInboundHandler:用于处理入站I/O事件;
ChannelOutboundHandler:用于处理出站I/O事件;

【ChannelHandlerContext】

保存Channel相关的所有上下文信息,同时关联一个ChannelHandler对象。

【ChannelPipeline】

保存ChannelHandler的List,用于处理拦截Channel的入站事件和出站操作。

ChannelPipeline实现了一种高级形式的拦截过滤器模式,使用户可以完成控制事件的处理方式,以及Channel中各个的ChannelHandler如何相互交互。

在Netty中每个Channel都有且仅有一个ChannelPipeline与之对应,他们的组成关系如下:

netty组件解析_第2张图片

一个channel包含一个ChannelPipeline,而ChannelPipeline中又维护了一个由ChannelHandlerContext组成的双向链表,并且每个ChannelHandlerContext中又关联着一个ChannelHandler。

read事件(入站事件)和write事件(出站事件)在一个双向链表中,入站事件会从链表head往后传递到最后一个入站的handler,出站事件会从链表tail往前传递到最前一个出站的handler,两种类型的handler互不干扰。

实例代码

maven引入:


	io.netty
	netty-all
	4.1.10.Final
	compile

服务端代码:

package com.weyne.cn.server;

import com.weyne.cn.handle.NettyServerHandler;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServer {
    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    public static void main(String[] args) {
        //1、创建两个线程组bossGroup和workerGroup,含有的子线程NioEventLoop的个数默认为cpu核数的两倍
        //一般bossGroup负责客户端连接,workerGroup工作线程组负责处理业务逻辑(客户端发送的数据),可一主多从(主流),也可多主
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(1);

        //2、创建服务端的启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();

        //3、使用链式编程配置参数
        //设置主线程、工作线程组
        bootstrap.group(bossGroup, workerGroup)
                //使用NioServerSocketChannel作为服务器的通道
                .channel(NioServerSocketChannel.class)
                //初始化服务器连接队列大小,服务器处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。
                //多个客户端同时来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer() { //创建通道初始化对象,设置初始化参数
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        //对workerGroup的socketchannel设置处理器
                        channel.pipeline().addLast(new NettyServerHandler());
                    }
                });
        logger.info("netty server start...");

        //绑定一个端口并同步启动服务器,生成一个channelFuture异步对象,sync方法是等待异步操作执行完毕
        ChannelFuture cf;
        try {
            cf = bootstrap.bind(9000).sync();
            //给channelFuture注册监听器,监听我们关心的事件
            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (cf.isSuccess()){
                        logger.info("监听端口9000成功");
                    }else {
                        logger.info("监听端口9000失败");
                    }
                }
            });
            //对通道关闭进行监听,closeFuture是异步操作,监听通道关闭
            //通过sync方法同步等待通道关闭处理完毕,这里会阻塞通道关闭完成
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException("netty server port error!");
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}

自定义handler需继承netty规定的某个handlerAdapter

package com.weyne.cn.handle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);

    /**
     * 读取客户端消息
     * @param ctx 上下文对象,含有通道channel,管道pipeline
     * @param msg 客户端数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("服务器读取线程:"+Thread.currentThread().getName());
        ByteBuf buf = (ByteBuf) msg;
        logger.info("读取客户端的消息为:"+buf.toString(CharsetUtil.UTF_8));
    }


    /**
     *  数据读取完毕处理方法
     * @param ctx 上下文对象
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("hello client", CharsetUtil.UTF_8);
        ctx.writeAndFlush(buf);
    }

    /**
     * 处理异常,一般需要关闭通道
     * @param ctx 上下文对象
     * @param cause 异常消息
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}

客户端代码:

package com.weyne.cn.client;

import com.weyne.cn.handle.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {
    private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);

    public static void main(String[] args) {
        EventLoopGroup clientGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(clientGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyClientHandler());
                    }
                });
        logger.info("netty client start");
        try {
            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException("服务端连接失败!");
        }finally {
            clientGroup.shutdownGracefully();
        }

    }
}

客户端handler

package com.weyne.cn.handle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("Hello server", CharsetUtil.UTF_8);
        ctx.writeAndFlush(buf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        logger.info("读取客户端的消息为:"+buf.toString(CharsetUtil.UTF_8));
        logger.info("客户端的地址为:"+ctx.channel().remoteAddress());

    }

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

Netty框架的目标就是让我们从网络基础应用编码中解脱出来,专注于业业务逻辑开发。

ByteBuf详解

ByteBuf是由一串字节数组构成。数组中的每个字节用来存放信息。

ByteBuf提供了两个索引,一个用于读取数据,一个用于写入数据。这两个索引通过字节数组中移动,来定位需要读取或写入的位置。

当ByteBuf读取时,他的readerlidex(读索引)将会根据读取的字节数递增,同样,当写入ByteBuf时,他的writerIndex也会根据写入的字节数进行递增。

netty组件解析_第3张图片

当readerlidex超过writerIndex位置时,会报IndexOutOfBoundsException。

当用ByteBuf.getByte(i)时,可重复取数据

但当ByteBuf.getByte()时,只会读取readerlidex位置及后面的数据,逐个字节读取,使用ByteBuf.writeByte(i)写数据,writerIndex也会随之递增。

EventLoopGroup

EventLoopGroup类图如下:

netty组件解析_第4张图片

EventLoopGroup上层有个ScheduledExecutorService( ExecutorService是jdk1.5引入),熟悉Scheduled的都知道,这是定时器任务,事件循环组,就是个定时器任务,实现了Iterable接口,具有链表的特性,可以将任务丢到下面执行

public interface EventLoopGroup extends EventExecutorGroup {
    /**
     * Return the next {@link EventLoop} to use
     */
    @Override
    EventLoop next();

    /**
     * Register a {@link Channel} with this {@link EventLoop}. The returned {@link ChannelFuture}
     * will get notified once the registration was complete.
     */
    ChannelFuture register(Channel channel);

    /**
     * Register a {@link Channel} with this {@link EventLoop} using a {@link ChannelFuture}. The passed
     * {@link ChannelFuture} will get notified once the registration was complete and also will get returned.
     */
    ChannelFuture register(ChannelPromise promise);

    /**
     * Register a {@link Channel} with this {@link EventLoop}. The passed {@link ChannelFuture}
     * will get notified once the registration was complete and also will get returned.
     *
     * @deprecated Use {@link #register(ChannelPromise)} instead.
     */
    @Deprecated
    ChannelFuture register(Channel channel, ChannelPromise promise);
}

next方法是把指针指向下一个县城,因为netty基于NIO,NIO之所以非阻塞,是因为用到了ForkJoinPool这种线程池

 

 

你可能感兴趣的:(分布式)