Netty权威指南(二)NIO模型

一、NIO编程

NIO有两种叫法:有人称之为New I/O;更多的人喜欢称之为Non-block I/O:非阻塞I/O,后者更能体现NIO的特点。
SocketServerSocket类相对应,NIO也提供了SocketChannelServerSocketChannel两种不同的套接字通道实现。这两种新增的通道都支持阻塞与非阻塞两种模式。一般来说:低负载、低并发的应用程序可以选择同步阻塞I/O以降低编程复杂度;对于高负载、高并发的应用程序,需要使用NIO的非阻塞模式进行开发。

二、NIO类库和相关概念

在Java1.4之前的早期版本,Java对I/O的支持并不完善,开发人员在开发高性能I/O程序的时候,会面临一些巨大的挑战和困难。主要问题如下:

  1. 没有数据缓冲区,I/O性能存在问题。
  2. 没有Channel通道的概念,只有输入和输出流。
  3. 同步阻塞式I/O通信(BIO),通常会导致通信线程被长时间阻塞。
  4. 支持的字符集有限,硬件可移植性不好。

NIO 主要有三大核心部分:Channel(通道),Buffer(缓冲区), Selector。传统 IO 基于字节流和字 符流进行操作,而 NIO 基于 Channel 和 Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。

NIO 和传统 IO 之间第一个最大的区别是,IO 是面向流的,NIO 是面向缓冲区的。

缓冲区Buffer

Buffer是一个对象,它包含一些要写入或者要读出的数据,在NIO类库中加入Buffer对象,体现了新库与原来I/O的一个重要区别。在面向流的IO中,可以将数据直接写入或者将数据直接得到Stream对象中。
在NIO库中,所有数据都是用缓冲区处理的,在读取数据时,他是直接读到缓冲区的;在写入数据时,写入带缓冲区中,任何时候访问NIO中的数据都是通过缓冲区进行操作。
缓冲区实质上是一个数组。通常它是一个字节数组(ByteBuffer),也可以使用其他种类的数组,但是一个缓冲区不仅仅是一个数组,缓冲区提供了对数据的结构化访问以及维护读写位置(limit)等信息。
最常用的是ByteBuffer,一个ByteBuffer提供了一组功能用于操作byte数组,每一种Java基本类型都对应有一种缓冲区(除了Boolean)。
ByteBuffer、CharBuffer、ShortBuffer、IntBuffer、LongBuffer、FloatBuffer、DoubleBuffer。

通道Channel

Channel是一个通道。它就像一个自来水管一样,网络数据通过Channel都读取和写入。通道和流的不同之处在于通道是双向的,流只是在一个方向上移动(一个流必须是InputStream或者OutputStream的子类)。而通道可以用于读、写或者二者同时进行。Channel是双全工的。同时支持读写操作。

多路复用器Selector

多路复用器Selector是JavaNIO编程的基础。简单来讲:Selector会不断轮询注册在其上的Channel,如果某个Channel上面发生事件,这个Channel就处于就绪状态,会被Selector轮询出来,然后通过SelectorKey可以获取就绪Channel的集合,进行后续的I/O操作。
一个多路复用器Selector可以同时轮询多个Channel,只需要一个线程负责Selector的轮询,就可以接入成百上千的客户端。

三、NIO服务端流程分析

  1. 打开ServerSocketChannel,用于监听客户端的连接,它是所有客户端连接的父管道。
  2. 绑定监听端口,设置连接为非阻塞模式。
  3. 创建Reactor线程创建多路复用器Selector并启动线程。
  4. ServerSocketChannel注册到Reactor线程的多路复用器Selector上,监听ACCEPT事件。
  5. 多路复用器Selector在线程run方法的无限循环体内轮询准备就绪的Key。
  6. 多路复用器Selector监听到有新的客户端接入,处理新的请求,完成TCP三次握手,建立物理链路。
  7. 设置客户端链路为非阻塞模式。
  8. 将新接入的客户端连接注册到Reactor线程的多路复用器上,监听操作。
  9. 异步读取客户端请求消息到缓冲区。
  10. 对ByteBuffer进行编解码,如果有半包消息指针reset,继续读取后续的报文,将解码成功的消息封装成Task,投递到业务线程池中,进行业务逻辑编排。
  11. 将POJO对象encode成ByteBuffer,调用SocketChannel的异步write接口,将消息异步发送给客户端。

四、NIO客户端流程分析

  1. 打开SocketChannel,绑定客户端本地地址。
  2. 设置SocketChannel为非阻塞模式。同时设置客户端连接的TCP参数
  3. 异步连接服务端
  4. 判断连接是否成功。如果连接成功,则直接注册读状态位到多路复用器Selector中,如果当前没有连接成功(异步连接,返回false,说明客户端已经发送sync包,服务端没有返回ack包,物理链路还没有建立)
  5. 向Reactor线程的多路复用器注册OP_CONNECT状态位,监听服务端的TCP ACK应答。
  6. 创建Reactor线程,创建多路复用器Selector并启动线程。
  7. 多路复用器在线程run方法的无限循环体内轮询准备就绪的key。
  8. 接收connect事件进行处理。
  9. 判断连接结果,如果连接成功,注册读事件到多路复用器。
  10. 异步读客户端请求消息到缓冲区。
  11. 对ByteBuffer进行编解码,如果有半包消息接收缓冲区Reset,继续读取后续的提交,将解码成功的消息封装成Task,投递到业务线程池中,进行业务逻辑编排。
  12. 将POJO对象encode成ByteBuffer,调用SocketChannel的异步write接口将消息异步发送给客户端。

在这里插入图片描述

五、NIO编程的优点

NIO编程的难度确实比同步阻塞的BIO编程大很多。我们的NIO实例没有考虑“半包读”和“半包写”,如果加上这些,代码将会更加复杂,既然代码这么复杂,为什么它的应用却越来越广泛呢?使用NIO编程的优点总结如下:

  1. 客户端发起的连接时异步的,可以通过在多路复用器注册OP_CONNECT等待后续结果,不需要像之的客户端那样被同步阻塞。
  2. SocketChannel的读写操作都是异步的,如果没有可读写的数据它不会同步等待,直接返回,这样IO通信线程就可以处理其他的链路,不需要同步等待这个链路可用。
  3. 线程模型的优化,由于JDK的Selector在Linux等主流操作系统上通过epoll实现,它没有连接句柄数的限制(只受限于操作系统的最大句柄数或者对单个进程的句柄限制),这意味着一个Selector线程可以同时处理成千上万个客户端连接,而且性能不会随着客户端的增加而线性下降,因此,它非常适合做高性能、高负载的网络服务器。

源码

TimeServer

创建一个多路复用类(MultiplexerTimeServer),是一个独立负责的线程,负责轮询多路复用器Selector,可以处理多个客户端的并发接入。

public class TimeServer {
    
    
    public static void main(String[] args) {
    
    
        int port = 8080;
        MultiplexerTimeServer timeServer =  new MultiplexerTimeServer(port);
        new Thread(timeServer,"NIO-MultiplexerTimeServer-001").start();
    }

}

MultiplexerTimeServer

package com.lsh.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @author :LiuShihao
 * @date :Created in 2021/3/1 12:03 下午
 * @desc :NIO时间服务器 MulitiplexerTimeServer  多路复用器
 * 它是一个独立的线程,负责轮询多路复用器Selector,可以处理多个客户端的并发接入。
 */
public class MultiplexerTimeServer implements Runnable{
    
    

    private Selector selector;

    private ServerSocketChannel serverChannel;

    private volatile boolean stop;

    /**
     * 初始化多路复用器 绑定监听端口
     * 创建多路复用器Selector、ServerSocketChannel
     * 对Channel和TCP参数进行配置
     * @param port
     */
    public MultiplexerTimeServer(int port) {
    
    
        try {
    
    
            //创建Reactor线程,创建多路复用器
            selector = Selector.open();
            //打开ServerSocketChannel,用于监听客户端的连接,它是所有客户端连接的父管道
            serverChannel = ServerSocketChannel.open();
            //将Channel设置为异步非阻塞模式,他的backlog设置为1024
            serverChannel.configureBlocking(false);
            //绑定监听接口
            serverChannel.socket().bind(new InetSocketAddress(port),1024);
            //将ServerSockrtChannel注册到Reactor线程的多路复用器Selector上,监听ACCEPT事件
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("The time server is start in port :"+port);

        } catch (IOException e) {
    
    
            e.printStackTrace();
            //如果资源初始化失败,如端口被占用,则退出
            System.exit(1);
        }

    }

    public void stop(){
    
    
        this.stop = true;
    }

    @Override
    public void run() {
    
    

        /**
         * 多路复用器在run方法的无限循环体中内轮询准备就绪的key
         * 在while循环体中,循环遍历selector,休眠时间为1秒,无论是否有读写时间发生,selector每隔1s都被唤醒1次
         * 当有处于就绪状态的Channel时,selector将返回该Channel的SelectionKey集合,通过对就绪状态的Channel集合进行迭代,可以进行网络的异步读写操作。
         */
        while(!stop){
    
    
            try {
    
    
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while(it.hasNext()){
    
    
                    key = it.next();
                    it.remove();
                    try{
    
    
                        handlerInput(key);
                    }catch (Exception e){
    
    
                        if (key != null){
    
    
                            key.cancel();
                            if (key.channel() != null){
    
    
                                key.channel().close();
                            }
                        }
                    }

                }

            } catch (Throwable t) {
    
    
                t.printStackTrace();
            }

        }
        //多路复用器关闭 后,所有注册在上面的Channel和Pipe等资源都会被自动用去注册并关闭,所以不需要重复释放资源
        if (selector != null){
    
    
            try {
    
    
                selector.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据SelectorKey的操作位进行判断即可获知网络时间的类型,
     * @param key
     * @throws IOException
     */
    private void handlerInput(SelectionKey key) throws IOException{
    
    
        if (key.isValid()){
    
    
            //处理新接入的消息请求
            if (key.isAcceptable()){
    
    
                //Accept the new connection
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                //通过ServerSocketChannel的accept接收客户端的链接请求并创建SocketChannel实例,相当于完成了TCP的三次握手,TCP物理链路正式建立。
                SocketChannel sc = ssc.accept();
                //需要将新创建的SocketChannel设置为异步非阻塞,同时也可以对其TCP参数进行设置,例如TCP接收和发送缓冲区的大小等,但作为入门的例子,没有进行额外的参数设置。
                sc.configureBlocking(false);
                // Add the new connection to the selector
                //将新接入的客户端连接注册到Reactor线程的多路复用器上,监听读操作,读取客户端发送的网络消息。
                sc.register(selector,SelectionKey.OP_READ);
            }
            if (key.isReadable()){
    
    
                //Read the data
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                // 异步读取客户端消息到缓冲区
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0){
    
    
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "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";
                    doWrite(sc,currentTime);
                } else if (readBytes < 0 ){
    
    
                    //对端链路关闭
                    key.cancel();
                    sc.close();
                }else {
    
    
                    ;//读到0字节,忽略
                }
            }

        }

    }

    private void doWrite(SocketChannel channel, String response) throws IOException{
    
    
        if (response != null && response.trim().length() > 0 ){
    
    
            //将消息encode成ByteBuffer,调用SocketChannel的异步write接口,将消息异步发送给客户端。
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer);
        }

    }
}

TimeClient

public class TimeClient {
    
    

    public static void main(String[] args) {
    
    
        int port = 8080;
        //通过创建TimeClient线程来处理异步连接和读写操作
        new Thread(new TimeClientHandle("127.0.0.1",port),"TimeClinet-001").start();
    }
}

TimeClientHandle

package com.lsh.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author :LiuShihao
 * @date :Created in 2021/3/1 2:18 下午
 * @desc :NIO时间服务器客户端 Handle
 */
public class TimeClientHandle  implements Runnable {
    
    
    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile  boolean stop;





    public TimeClientHandle(String host, int port) {
    
    
        this.host = host == null ? "127.0.0.1" : host;
        this.port = port;
        try {
    
    
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
    
    
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
    
    
        try{
    
    
            doConnect();
        }catch (Exception e){
    
    
            e.printStackTrace();
            System.exit(1);
        }
        while(!stop){
    
    
            try{
    
    
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while(it.hasNext()){
    
    
                    key = it.next();
                    it.remove();
                    try{
    
    
                        handleInput(key);
                    }catch (Exception e){
    
    
                        if (key != null){
    
    
                            key.cancel();
                            if (key.channel() != null){
    
    
                                key.channel().close();
                            }
                        }
                    }
                }
            }catch (Exception e){
    
    
                e.printStackTrace();
                System.exit(1);
            }
        }
        // 多路复用器关闭后,所有注册在上面的Channel和Pige等资源都会被自动去注册并关闭,所以不需要重读释放资源。
        if (selector != null){
    
    
            try{
    
    
                selector.close();
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }

    }

    private void handleInput(SelectionKey key) throws IOException{
    
    
        if (key.isValid()){
    
    
            //判断是否连接成功
            SocketChannel sc = (SocketChannel) key.channel();
            if (key.isConnectable()){
    
    
                if (sc.finishConnect()){
    
    
                    sc.register(selector,SelectionKey.OP_READ);
                    doWrite(sc);
                }else {
    
    
                    //连接失败,进程退出
                    System.exit(1);
                }
            }
            if (key.isReadable()){
    
    
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0 ){
    
    
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes,"UTF-8");
                    System.out.println("Now is :"+body);
                    this.stop = true;
                } else if (readBytes < 0 ){
    
    
                    key.cancel();
                    sc.close();
                }else {
    
    
                    ;//读到0字节,忽略
                }

            }
        }

    }



    private void doConnect() throws IOException{
    
    
        //如果直接连接成功,则注册到多路复用器上,发送请求消息,读应答
        if (socketChannel.connect(new InetSocketAddress(host,port))){
    
    
            socketChannel.register(selector,SelectionKey.OP_READ);
            doWrite(socketChannel);
        }else {
    
    
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }

    private void doWrite(SocketChannel sc) throws IOException{
    
    
        byte[] req = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        sc.write(writeBuffer);
        if (!writeBuffer.hasRemaining()){
    
    
            System.out.println("Send order 2 server succeed.");
        }

    }
}

猜你喜欢

转载自blog.csdn.net/DreamsArchitects/article/details/113934075