nio 原理

来源:互联网 发布:马库斯斯玛特体测数据 编辑:程序博客网 时间:2024/06/08 07:53

说明:nio理论及例子,了解nio的可以跳过本文看Hadoop的rpc实现,建议新手看看

一、阻塞式BIO的缺点:

前面自己实现了一个阻塞式BIO服务,采 用BIO通信模型的服务端,通常由一个独立的Acceptor线程负责监听客户端的连接,接收到客户端连接之后为客户端连接创建一个新的线程处理请求消 息,处理完成之后,返回应答消息给客户端,线程销毁,这就是典型的一请求一应答模型。该架构最大的问题就是不具备弹性伸缩能力,当并发访问量增加后,服务 端的线程个数和并发访问数成线性正比,由于线程是Java虚拟机非常宝贵的系统资源,当线程数膨胀之后,系统的性能急剧下降,随着并发量的继续增加,可能 会发生句柄溢出、线程堆栈溢出等问题,并导致服务器最终宕机。(http://www.open-open.com/lib/view/open1403057331075.html)

根据阻塞I/O通信模型,它的两缺点:
1. 当客户端多时,会创建大量的处理线程。且每个线程都要占用栈空间和一些CPU时间
2. 阻塞可能带来频繁的上下文切换,且大部分上下文切换可能是无意义的。


(本图来自http://www.open-open.com/lib/view/open1403057331075.html)

二、异步非阻塞通信的引入

在 IO编程过程中,当需要同时处理多个客户端接入请求时,可以利用多线程或者IO多路复用技术进行处理。IO多路复用技术通过把多个IO的阻塞复用到同一个 select的阻塞上,从而使得系统在单线程的情况下可以同时处理多个客户端请求。与传统的多线程/多进程模型比,I/O多路复用的最大优势是系统开销 小,系统不需要创建新的额外进程或者线程,也不需要维护这些进程和线程的运行,降低了系统的维护工作量,节省了系统资源。JDK1.4提供了对非阻塞IO(NIO)的支持,JDK1.5_update10版本使用epoll替代了传统的select/poll,极大的提升了NIO通信的性能。

关于NIO知识详细见:点击打开链接 http://blog.csdn.net/lzlchangqi/article/details/41209719
java NIO的工作原理:
1. 由一个专门的线程来处理所有的 IO 事件,并负责分发。 
2. 事件驱动机制:事件到的时候触发,而不是同步的去监视事件。 
3. 线程通讯:线程之间通过 wait,notify 等方式通讯。保证每次上下文切换都是有意义的。减少无谓的线程切换。

如下图:一个线程Reactor用来处理所有io,并分发read、write等事件


                                             (本图来自互联网)

三:结合互联网的例子进行分析NIO:

1、先看例子的源代码,不妨debug调试下

[html] view plain copy 在CODE上查看代码片派生到我的代码片
  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.net.ServerSocket;  
  4. import java.nio.ByteBuffer;  
  5. import java.nio.channels.SelectionKey;  
  6. import java.nio.channels.Selector;  
  7. import java.nio.channels.ServerSocketChannel;  
  8. import java.nio.channels.SocketChannel;  
  9. import java.util.Iterator;  
  10. import java.util.Set;  
  11.   
  12. public class NIOServer {  
  13.       
  14.     /*标识数字*/  
  15.     private  int flag = 0;  
  16.     /*缓冲区大小*/  
  17.     private  int BLOCK = 4096;  
  18.     /*接受数据缓冲区*/  
  19.     private  ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*发送数据缓冲区*/  
  21.     private  ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  22.     private  Selector selector;  
  23.   
  24.     public NIOServer(int port) throws IOException {  
  25.         // 1、打开服务器套接字通道  
  26.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
  27.         // 服务器配置为非阻塞  
  28.         serverSocketChannel.configureBlocking(false);  
  29.         // 检索与此通道关联的服务器套接字  
  30.         ServerSocket serverSocket = serverSocketChannel.socket();  
  31.         //2、 进行服务的绑定  
  32.         serverSocket.bind(new InetSocketAddress(port));  
  33.         //3、 通过open()方法找到Selector  
  34.         selector = Selector.open();  
  35.         //4、注册到selector,等待连接  
  36.         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  
  37.         System.out.println("Server Start----8888:");  
  38.     }  
  39.   
  40.   
  41.     // 监听  
  42.     private void listen() throws IOException {  
  43.         while (true) {  
  44.             // 选择一组键,并且相应的通道已经打开  
  45.             selector.select();  
  46.             // 返回此选择器的已选择键集。  
  47.             Set<SelectionKey> selectionKeys = selector.selectedKeys();  
  48.             Iterator<SelectionKey> iterator = selectionKeys.iterator();  
  49.             //5 轮询就绪的key  
  50.             while (iterator.hasNext()) {          
  51.                 SelectionKey selectionKey = iterator.next();  
  52.                 iterator.remove();  
  53.                 handleKey(selectionKey);  
  54.             }  
  55.         }  
  56.     }  
  57.   
  58.     // 处理请求  
  59.     private void handleKey(SelectionKey selectionKey) throws IOException {  
  60.         // 接受请求  
  61.         ServerSocketChannel server = null;  
  62.         SocketChannel client = null;  
  63.         String receiveText;  
  64.         String sendText;  
  65.         int count=0;  
  66.         // 测试此键的通道是否已准备好接受新的套接字连接。  
  67.         //步骤6 handle connect 处理新的客户接入  
  68.         if (selectionKey.isAcceptable()) {  
  69.             // 返回为之创建此键的通道。  
  70.             //步骤7 设置新建连接的socket  
  71.             server = (ServerSocketChannel) selectionKey.channel();  
  72.             // 接受到此通道套接字的连接。  
  73.             // 此方法返回的套接字通道(如果有)将处于阻塞模式。  
  74.             client = server.accept();  
  75.             // 配置为非阻塞  
  76.             client.configureBlocking(false);  
  77.             //步骤8   注册到selector,等待连接  
  78.             client.register(selector, SelectionKey.OP_READ);  
  79.         } else if (selectionKey.isReadable()) {//步骤9:异步处理请求消息到ByteBuffer(),代码中没有步骤10  
  80.             // 返回为之创建此键的通道。  
  81.             client = (SocketChannel) selectionKey.channel();  
  82.             //将缓冲区清空以备下次读取  
  83.             receivebuffer.clear();  
  84.             //读取服务器发送来的数据到缓冲区中  
  85.             count = client.read(receivebuffer);   
  86.             if (count > 0) {  
  87.                 receivebuffer.flip();  
  88.                 byte[] bytes = new byte[receivebuffer.remaining()];  
  89.                 receivebuffer.get(bytes);  
  90.                 receiveText = new String(bytes,"utf-8");  
  91.                 System.out.println("服务器端接受客户端数据--:"+receiveText);  
  92.                 client.register(selector, SelectionKey.OP_WRITE);  
  93.             }  
  94.         } else if (selectionKey.isWritable()) {//步骤11 异步写  
  95.             //将缓冲区清空以备下次写入  
  96.             sendbuffer.clear();  
  97.             // 返回为之创建此键的通道。  
  98.             client = (SocketChannel) selectionKey.channel();  
  99.             sendText="message from server--" + flag++;  
  100.             //向缓冲区中输入数据  
  101.             sendbuffer.put(sendText.getBytes());  
  102.              //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位  
  103.             sendbuffer.flip();  
  104.             //输出到通道  
  105.             client.write(sendbuffer);  
  106.             System.out.println("服务器端向客户端发送数据--:"+sendText);  
  107.             client.register(selector, SelectionKey.OP_READ);  
  108.         }  
  109.     }  
  110.   
  111.     /**  
  112.      * @param args  
  113.      * @throws IOException  
  114.      */  
  115.     public static void main(String[] args) throws IOException {  
  116.         // TODO Auto-generated method stub  
  117.         int port = 8888;  
  118.         NIOServer server = new NIOServer(port);  
  119.         server.listen();  
  120.     }  
  121. }  

[html] view plain copy 在CODE上查看代码片派生到我的代码片
  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.nio.ByteBuffer;  
  4. import java.nio.channels.SelectionKey;  
  5. import java.nio.channels.Selector;  
  6. import java.nio.channels.SocketChannel;  
  7. import java.util.Iterator;  
  8. import java.util.Set;  
  9.   
  10. public class NIOClient {  
  11.   
  12.     /*标识数字*/  
  13.     private static int flag = 0;  
  14.     /*缓冲区大小*/  
  15.     private static int BLOCK = 4096;  
  16.     /*接受数据缓冲区*/  
  17.     private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  18.     /*发送数据缓冲区*/  
  19.     private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*服务器端地址*/  
  21.     private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress(  
  22.             "localhost", 8888);  
  23.   
  24.     public static void main(String[] args) throws IOException {  
  25.         // TODO Auto-generated method stub  
  26.         //步骤1  打开socket的通道socketChannel  
  27.         SocketChannel socketChannel = SocketChannel.open();  
  28.         //步骤2  设置为非阻塞方式,同时设置tcp参数  
  29.         socketChannel.configureBlocking(false);  
  30.         Selector selector = null;  
  31.           
  32.           
  33.         // 异步连接服务器  
  34.         if (socketChannel.connect(SERVER_ADDRESS)) {  
  35.               
  36.         }  
  37.         else {  
  38.             //步骤5  注册连接服务端socket动作  
  39.             selector = Selector.open();  
  40.             socketChannel.register(selector, SelectionKey.OP_CONNECT);  
  41.         }     
  42.         // 分配缓冲区大小内存  
  43.           
  44.           
  45.         Set<SelectionKey> selectionKeys;  
  46.         Iterator<SelectionKey> iterator;  
  47.         SelectionKey selectionKey;  
  48.         SocketChannel client;  
  49.         String receiveText;  
  50.         String sendText;  
  51.         int count=0;  
  52.                //步骤6 启动线程  
  53.         while (true) {  
  54.             //选择一组键,其相应的通道已为 I/O 操作准备就绪。  
  55.             //此方法执行处于阻塞模式的选择操作。  
  56.             int ret = selector.select();  
  57.             //System.out.println(ret);  
  58.               
  59.             //返回此选择器的已选择键集。  
  60.             selectionKeys = selector.selectedKeys();  
  61.             //System.out.println(selectionKeys.size());  
  62.             iterator = selectionKeys.iterator();  
  63.             while (iterator.hasNext()) {//7 轮询就绪的key  
  64.                 selectionKey = iterator.next();  
  65.                 //4  判断连接结果,如果连接成功,跳到步骤10,如果不成功,执行步骤5  
  66.                 if (selectionKey.isConnectable()) {  
  67.                     System.out.println("client connect");  
  68.                     client = (SocketChannel) selectionKey.channel();  
  69.                     // 判断此通道上是否正在进行连接操作。  
  70.                     // 完成套接字通道的连接过程。8 handle connect()  
  71.                     if (client.isConnectionPending()) {  
  72.                         client.finishConnect();//9 判断连接完成,完成连接  
  73.                         System.out.println("完成连接!");  
  74.                         sendbuffer.clear();  
  75.                         sendbuffer.put("Hello,Server".getBytes());  
  76.                         sendbuffer.flip();  
  77.                         client.write(sendbuffer);  
  78.                     }  
  79.                     //步骤10 向多路复用器注册 OP_READ  
  80.                     client.register(selector, SelectionKey.OP_READ);  
  81.                 } else if (selectionKey.isReadable()) {//步骤11 handle read() 异步读请求消息到ByteBuffer  
  82.                     client = (SocketChannel) selectionKey.channel();  
  83.                     //将缓冲区清空以备下次读取  
  84.                     receivebuffer.clear();  
  85.                     //读取服务器发送来的数据到缓冲区中  
  86.                     count=client.read(receivebuffer);  
  87.                     if(count>0){  
  88.                         receiveText = new String( receivebuffer.array(),0,count);  
  89.                         System.out.println("客户端接受服务器端数据--:"+receiveText);  
  90.                         client.register(selector, SelectionKey.OP_WRITE);  
  91.                     }  
  92.   
  93.                 } else if (selectionKey.isWritable()) {//步骤13  异步写ByteBuffer到SocketChannel  
  94.                     sendbuffer.clear();  
  95.                     client = (SocketChannel) selectionKey.channel();  
  96.                     sendText = "message from client--" + (flag++);  
  97.                     sendbuffer.put(sendText.getBytes());  
  98.                      //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位  
  99.                     sendbuffer.flip();  
  100.                     client.write(sendbuffer);  
  101.                     System.out.println("客户端向服务器端发送数据--:"+sendText);  
  102.                     client.register(selector, SelectionKey.OP_READ);  
  103.                 }  
  104.             }  
  105.             selectionKeys.clear();  
  106.         }  
  107.     }  
  108. }  

2、代码可用如下图说明(图片来自:http://www.open-open.com/lib/view/open1403057331075.html)

       注意:通过debug可以发现Server端handle read后,就直接进行了步骤13,异步写操作,这是因为在步骤11进行了write的注册,因此它不需要client的触发,这就是selector轮询的作用。

按照Reactor模式设计和实现,它的服务端通信序列图如下:


客户端通信序列图如下:

客户端步骤4-6的标注有些牵强,其实在大的程序中是这样的,如hadoop的ipc代码中就是这样,稍后文章会讲解hadoop如何使用nio进行rpc通信。

0 0