Java并发编程之NIO简明教程

nspg6799 7年前
   <p>在传统的架构中,对于客户端的每一次请求,服务器都会创建一个新的线程或者利用线程池复用去处理用户的一个请求,然后返回给用户结果,这样做在高并发的情况下会存在非常严重的性能问题:对于用户的每一次请求都创建一个新的线程是需要一定内存的,同时线程之间频繁的上下文切换也是一个很大的开销。</p>    <p>p.s: 本文涉及的完整实例代码都可以在我的 <a href="/misc/goto?guid=4959751646541403353" rel="nofollow,noindex">GitHub</a> 上面下载。</p>    <h2>什么是Selector</h2>    <p>NIO的核心就是Selector,读懂了Selector就理解了异步机制的实现原理,下面先来简单的介绍一下什么是Selector。现在对于客户端的每一次请求到来时我们不再立即创建一个线程进行处理,相反以epool为例子当一个事件准备就绪之后通过回调机制将描述符加入到阻塞队列中,下面只需要通过遍历阻塞队列对相应的事件进行处理就行了,通过这种回调机制整个过程都不需要对于每一个请求都去创建一个线程去单独处理。上面的解释还是有些抽象,下面我会通过具体的代码实例来解释,在这之前我们先来了解一下NIO中两个基础概念Buffer和Channel。</p>    <p>如果大家对于多路IO复用比如select/epool完全没有陌生的话,建议先读一下我的这篇Linux下的五种IO模型 :-)</p>    <h2>Buffer</h2>    <p>以ByteBuffer为例子,我们可以通过ByteBuffer.allocate(n)来分配n个字节的缓冲区,对于缓冲区有四个重要的属性:</p>    <ol>     <li>capacity,缓冲区的容量,也就是我们上面指定的n。</li>     <li>position,当前指针指向的位置。</li>     <li>mark,前一个位置,这里我们下面再解释。</li>     <li>limit,最大能读取或者写入的位置。</li>    </ol>    <p><img src="https://simg.open-open.com/show/506869f9bfa5f260b1a477ff5b0b0a9f.png"></p>    <p>如上图所示,Buffer实际上也是分为两种,一种用于写数据,一种用于读取数据。</p>    <h3>put</h3>    <p>通过直接阅读ByteBuffer源码可以清晰看出put方法是把一个byte变量x放到缓冲区中去,同时position加1:</p>    <pre>  <code class="language-java">publicByteBufferput(bytex){      hb[ix(nextPutIndex())] = x;      return this;  }    final int nextPutIndex(){      if (position >= limit)          throw new BufferOverflowException();      return position++;  }  </code></pre>    <h3>get</h3>    <p>get方法是从缓冲区中读取一个字节,同时position加一:</p>    <pre>  <code class="language-java">public byte get(){      return hb[ix(nextGetIndex())];  }    final int nextGetIndex(){      if (position >= limit)          throw new BufferUnderflowException();      return position++;  }  </code></pre>    <h3>flip</h3>    <p>如果我们想将buffer从写数据的情况变成读数据的情况,可以直接使用flip方法:</p>    <pre>  <code class="language-java">public finalBufferflip(){      limit = position;      position = 0;      mark = -1;      return this;  }  </code></pre>    <h3>mark和reset</h3>    <p>mark是记住当前的位置用的,也就是保存position的值:</p>    <pre>  <code class="language-java">public finalBuffermark(){      mark = position;      return this;  }  </code></pre>    <p>如果我们在对缓冲区读写之前就调用了mark方法,那么以后当position位置变化之后,想回到之前的位置可以调用reset会将mark的值重新赋给position:</p>    <pre>  <code class="language-java">public finalBufferreset(){      int m = mark;      if (m < 0)          throw new InvalidMarkException();      position = m;      return this;  }  </code></pre>    <h2>Channel</h2>    <p><img src="https://simg.open-open.com/show/654a17932b5ea308f73200f077e6a4cb.png"></p>    <p>利用NIO,当我们读取数据的时候,会先从buffer加载到channel,而写入数据的时候,会先入到channel然后通过channel转移到buffer中去。channel给我们提供了两个方法:通过 channel.read(buffer) 可以将channel中的数据写入到buffer中,而通过 channel.write(buffer) 则可以将buffer中的数据写入到到channel中。</p>    <p>Channel的话分为四种:</p>    <ol>     <li>FileChannel从文件中读写数据。</li>     <li>DatagramChannel以UDP的形式从网络中读写数据。</li>     <li>SocketChannel以TCP的形式从网络中读写数据。</li>     <li>ServerSocketChannel允许你监听TCP连接。</li>    </ol>    <p>因为今天我们的重点是Selector,所以来看一下SocketChannel的用法。在下面的代码利用SocketChannel模拟了一个简单的server-client程序</p>    <p>WebServer 的代码如下,和传统的sock程序并没有太多的差异,只是我们引入了buffer和channel的概念:</p>    <pre>  <code class="language-java">ServerSocketChannel ssc = ServerSocketChannel.open();  ssc.socket().bind(new InetSocketAddress("127.0.0.1", 5000));  SocketChannel socketChannel = ssc.accept();    ByteBuffer readBuffer = ByteBuffer.allocate(128);  socketChannel.read(readBuffer);    readBuffer.flip();  while (readBuffer.hasRemaining()) {      System.out.println((char)readBuffer.get());  }    socketChannel.close();  ssc.close();  </code></pre>    <p>WebClient 的代码如下:</p>    <pre>  <code class="language-java">SocketChannel socketChannel = null;  socketChannel = SocketChannel.open();  socketChannel.connect(new InetSocketAddress("127.0.0.1", 5000));    ByteBuffer writeBuffer = ByteBuffer.allocate(128);  writeBuffer.put("hello world".getBytes());    writeBuffer.flip();  socketChannel.write(writeBuffer);  socketChannel.close();  </code></pre>    <h3>Scatter / Gather</h3>    <p>在上面的client程序中,我们也可以同时将多个buffer中的数据放入到一个数组后然后统一放入到channel后传递给服务器:</p>    <pre>  <code class="language-java">ByteBuffer buffer1 = ByteBuffer.allocate(128);  ByteBuffer buffer2 = ByteBuffer.allocate(16);  buffer1.put("hello ".getBytes());  buffer2.put("world".getBytes());    buffer1.flip();  buffer2.flip();  ByteBuffer[] bufferArray = {buffer1, buffer2};  socketChannel.write(bufferArray);  </code></pre>    <h2>Selector</h2>    <p><img src="https://simg.open-open.com/show/ed571e5b8793cae275479b761393a6f0.png"></p>    <p>通过使用selector,我们可以通过一个线程来同时管理多个channel,省去了创建线程以及线程之间进行上下文切换的开销。</p>    <h3>创建一个selector</h3>    <p>通过调用selector类的静态方法open我们就可以创建一个selector对象:</p>    <pre>  <code class="language-java">Selector selector = Selector.open();  </code></pre>    <h3>注册channel</h3>    <p>为了保证selector能够监听多个channel,我们需要将channel注册到selector当中:</p>    <pre>  <code class="language-java">channel.configureBlocking(false);  SelectionKey key = channel.register(selector, SelectionKey.OP_READ);  </code></pre>    <p>我们可以监听四种事件:</p>    <ol>     <li>SelectionKey.OP_CONNECT:当客户端的尝试连接到服务器</li>     <li>SelectionKey.OP_ACCEPT:当服务器接受来自客户端的请求</li>     <li>SelectionKey.OP_READ:当服务器可以从channel中读取数据</li>     <li>SelectionKey.OP_WRITE:当服务器可以向channel中写入数据</li>    </ol>    <p>对SelectorKey调用 channel 方法可以得到key对应的channel:</p>    <pre>  <code class="language-java">Channel channel = key.channel();  </code></pre>    <p>而key自身感兴趣的监听事件也可以通过 interestOps 来获得:</p>    <pre>  <code class="language-java">int interestSet = selectionKey.interestOps();  </code></pre>    <p>对selector调用 selectedKeys() 方法我们可以得到注册的所有key:</p>    <pre>  <code class="language-java">Set<SelectionKey> selectedKeys = selector.selectedKeys();  </code></pre>    <h2>实战</h2>    <p>服务器的代码如下:</p>    <pre>  <code class="language-java">ServerSocketChannel ssc = ServerSocketChannel.open();  ssc.socket().bind(new InetSocketAddress("127.0.0.1", 5000));  ssc.configureBlocking(false);    Selector selector = Selector.open();  ssc.register(selector, SelectionKey.OP_ACCEPT);    ByteBuffer readBuff = ByteBuffer.allocate(128);  ByteBuffer writeBuff = ByteBuffer.allocate(128);  writeBuff.put("received".getBytes());  writeBuff.flip(); // make buffer ready for reading    while (true) {      selector.select();      Set<SelectionKey> keys = selector.selectedKeys();      Iterator<SelectionKey> it = keys.iterator();        while (it.hasNext()) {          SelectionKey key = it.next();          it.remove();            if (key.isAcceptable()) {              SocketChannel socketChannel = ssc.accept();              socketChannel.configureBlocking(false);              socketChannel.register(selector, SelectionKey.OP_READ);          } else if (key.isReadable()) {              SocketChannel socketChannel = (SocketChannel) key.channel();              readBuff.clear(); // make buffer ready for writing              socketChannel.read(readBuff);              readBuff.flip(); // make buffer ready for reading              System.out.println(new String(readBuff.array()));              key.interestOps(SelectionKey.OP_WRITE);          } else if (key.isWritable()) {                  writeBuff.rewind(); // sets the position back to 0                  SocketChannel socketChannel = (SocketChannel) key.channel();                  socketChannel.write(writeBuff);                  key.interestOps(SelectionKey.OP_READ);          }      }  }  </code></pre>    <p>客户端程序的代码如下,各位读者可以同时在终端下面多开几个程序来同时模拟多个请求,而对于多个客户端的程序我们的服务器始终只用一个线程来处理多个请求。一个很常见的应用场景就是多个用户同时往服务器上传文件,对于每一个上传请求我们不在单独去创建一个线程去处理,同时利用Executor/Future我们也可以不用阻塞在IO操作中而是立即返回用户结果。</p>    <pre>  <code class="language-java">SocketChannel socketChannel = SocketChannel.open();  socketChannel.connect(new InetSocketAddress("127.0.0.1", 5000));    ByteBuffer writeBuffer = ByteBuffer.allocate(32);  ByteBuffer readBuffer = ByteBuffer.allocate(32);    writeBuffer.put("hello".getBytes());  writeBuffer.flip(); // make buffer ready for reading    while (true) {      writeBuffer.rewind(); // sets the position back to 0      socketChannel.write(writeBuffer); // hello      readBuffer.clear(); // make buffer ready for writing      socketChannel.read(readBuffer); // recieved  }  </code></pre>    <p> </p>    <p>来自:https://www.ziwenxie.site/2017/08/22/java-nio/</p>    <p> </p>