使用Java NIO编写高性能的服务器

开发 后端
从JDK 1.4开始,Java的标准库中就包含了NIO,即所谓的“New IO”。其中最重要的功能就是提供了“非阻塞”的IO,当然包括了Socket。NonBlocking的IO就是对select(Unix平台下)以及 WaitForMultipleObjects(Windows平台)的封装,提供了高性能、易伸缩的服务架构。

从JDK 1.4开始,Java的标准库中就包含了NIO,即所谓的“New IO”。其中最重要的功能就是提供了“非阻塞”的IO,当然包括了Socket。NonBlocking的IO就是对select(Unix平台下)以及 WaitForMultipleObjects(Windows平台)的封装,提供了高性能、易伸缩的服务架构。

说来惭愧,直到JDK1.4才有这种功能,但迟到者不一定没有螃蟹吃,NIO就提供了优秀的面向对象的解决方案,可以很方便地编写高性能的服务器。

话说回来,传统的Server/Client实现是基于Thread per request,即服务器为每个客户端请求建立一个线程处理,单独负责处理一个客户的请求。比如像Tomcat(新版本也会提供NIO方案)、Resin等Web服务器就是这样实现的。当然为了减少瞬间峰值问题,服务器一般都使用线程池,规定了同时并发的最大数量,避免了线程的无限增长。

但这样有一个问题:如果线程池的大小为100,当有100个用户同时通过HTTP现在一个大文件时,服务器的线程池会用完,因为所有的线程都在传输大文件了,即使第101个请求者仅仅请求一个只有10字节的页面,服务器也无法响应了,只有等到线程池中有空闲的线程出现。

另外,线程的开销也是很大的,特别是达到了一个临界值后,性能会显著下降,这也限制了传统的Socket方案无法应对并发量大的场合,而“非阻塞”的IO就能轻松解决这个问题。

下面只是一个简单的例子:服务器提供了下载大型文件的功能,客户端连接上服务器的12345端口后,就可以读取服务器发送的文件内容信息了。注意这里的服务器只有一个主线程,没有其他任何派生线程,让我们看看NIO是如何用一个线程处理N个请求的。

NIO服务器最核心的一点就是反应器模式:当有感兴趣的事件发生的,就通知对应的事件处理器去处理这个事件,如果没有,则不处理。所以使用一个线程做轮询就可以了。当然这里这是个例子,如果要获得更高性能,可以使用少量的线程,一个负责接收请求,其他的负责处理请求,特别是对于多CPU时效率会更高。

关于使用NIO过程中出现的问题,最为普遍的就是为什么没有请求时CPU的占用率为100%?出现这种问题的主要原因是注册了不感兴趣的事件,比如如果没有数据要发到客户端,而又注册了写事件(OP_WRITE),则在 Selector.select()上就会始终有事件出现,CPU就一直处理了,而此时select()应该是阻塞的。

另外一个值得注意的问题是:由于只使用了一个线程(多个线程也如此)处理用户请求,所以要避免线程被阻塞,解决方法是事件的处理者必须要即刻返回,不能陷入循环中,否则会影响其他用户的请求速度。

具体到本例子中,由于文件比较大,如果一次性发送整个文件(这里的一次性不是指send整个文件内容,而是通过while循环不间断的发送分组包),则主线程就会阻塞,其他用户就不能响应了。这里的解决方法是当有WRITE事件时,仅仅是发送一个块(比如4K字节)。发完后,继续等待WRITE事件出现,依次处理,直到整个文件发送完毕,这样就不会阻塞其他用户了。

服务器的例子:

  1. package nio.file;     
  2. import java.io.FileInputStream;     
  3. import java.io.IOException;     
  4. import java.net.InetSocketAddress;     
  5. import java.nio.ByteBuffer;     
  6. import java.nio.CharBuffer;      
  7. import java.nio.channels.FileChannel;     
  8. import java.nio.channels.SelectionKey;     
  9. import java.nio.channels.Selector;     
  10. import java.nio.channels.ServerSocketChannel;     
  11. import java.nio.channels.SocketChannel;     
  12. import java.nio.charset.Charset;     
  13. import java.nio.charset.CharsetDecoder;     
  14. import java.util.Iterator;      
  15. /**     
  16. * 测试文件下载的NIOServer     
  17. *     
  18. * @author tenyears.cn     
  19. */    
  20. public class NIOServer {      
  21. static int BLOCK = 4096;      
  22. // 处理与客户端的交互     
  23. public class HandleClient {     
  24. protected FileChannel channel;      
  25. protected ByteBuffer buffer;     
  26. public HandleClient() throws IOException {     
  27. this.channel = new FileInputStream(filename).getChannel();      
  28. this.buffer = ByteBuffer.allocate(BLOCK);      
  29. }      
  30. public ByteBuffer readBlock() {     
  31. try {     
  32. buffer.clear();      
  33. int count = channel.read(buffer);      
  34. buffer.flip();      
  35. if (count <= 0)      
  36. return null;      
  37. catch (IOException e) {     
  38. e.printStackTrace();      
  39. }     
  40. return buffer;      
  41. }     
  42. public void close() {     
  43. try {     
  44. channel.close();     
  45. catch (IOException e) {      
  46. e.printStackTrace();     
  47. }     
  48. }     
  49. }      
  50. protected Selector selector;      
  51. protected String filename = "d:\\bigfile.dat"// a big file      
  52. protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);     
  53. protected CharsetDecoder decoder;     
  54. public NIOServer(int port) throws IOException {     
  55. selector = this.getSelector(port);     
  56. Charset charset = Charset.forName("GB2312");      
  57. decoder = charset.newDecoder();      
  58. }     
  59. // 获取Selector     
  60. protected Selector getSelector(int port) throws IOException {     
  61. ServerSocketChannel server = ServerSocketChannel.open();     
  62. Selector sel = Selector.open();     
  63. server.socket().bind(new InetSocketAddress(port));     
  64. server.configureBlocking(false);     
  65. server.register(sel, SelectionKey.OP_ACCEPT);     
  66. return sel;      
  67. }      
  68. // 监听端口     
  69. public void listen() {     
  70. try {     
  71. for (;;) {     
  72. selector.select();     
  73. Iterator iter = selector.selectedKeys()     
  74. .iterator();     
  75. while (iter.hasNext()) {     
  76. SelectionKey key = iter.next();     
  77. iter.remove();     
  78. handleKey(key);     
  79. }     
  80. }     
  81. catch (IOException e) {     
  82. e.printStackTrace();      
  83. }      
  84. }      
  85. // 处理事件      
  86. protected void handleKey(SelectionKey key) throws IOException {     
  87. if (key.isAcceptable()) { // 接收请求     
  88. ServerSocketChannel server = (ServerSocketChannel) key.channel();     
  89. SocketChannel channel = server.accept();     
  90. channel.configureBlocking(false);      
  91. channel.register(selector, SelectionKey.OP_READ);      
  92. else if (key.isReadable()) { // 读信息      
  93. SocketChannel channel = (SocketChannel) key.channel();      
  94. int count = channel.read(clientBuffer);     
  95. if (count > 0) {     
  96. clientBuffer.flip();     
  97. CharBuffer charBuffer = decoder.decode(clientBuffer);     
  98. System.out.println("Client >>" + charBuffer.toString());      
  99. SelectionKey wKey = channel.register(selector,      
  100. SelectionKey.OP_WRITE);      
  101. wKey.attach(new HandleClient());      
  102. else    
  103. channel.close();      
  104. clientBuffer.clear();     
  105. else if (key.isWritable()) { // 写事件     
  106. SocketChannel channel = (SocketChannel) key.channel();     
  107. HandleClient handle = (HandleClient) key.attachment();      
  108. ByteBuffer block = handle.readBlock();      
  109. if (block != null)      
  110. channel.write(block);     
  111. else {     
  112. handle.close();     
  113. channel.close();      
  114. }     
  115. }      
  116. }     
  117. public static void main(String[] args) {     
  118. int port = 12345;     
  119. try {     
  120. NIOServer server = new NIOServer(port);     
  121. System.out.println("Listernint on " + port);     
  122. while (true) {     
  123. server.listen();     
  124. }     
  125. catch (IOException e) {      
  126. e.printStackTrace();      
  127. }      
  128. }     
  129. }    

该代码中,通过一个HandleClient来获取文件的一块数据,每一个客户都会分配一个HandleClient的实例。

下面是客户端请求的代码,也比较简单,模拟100个用户同时下载文件。

  1. package nio.file;     
  2. import java.io.IOException;     
  3. import java.net.InetSocketAddress;      
  4. import java.nio.ByteBuffer;      
  5. import java.nio.CharBuffer;      
  6. import java.nio.channels.SelectionKey;     
  7. import java.nio.channels.Selector;      
  8. import java.nio.channels.SocketChannel;      
  9. import java.nio.charset.Charset;      
  10. import java.nio.charset.CharsetEncoder;      
  11. import java.util.Iterator;     
  12. import java.util.concurrent.ExecutorService;      
  13. import java.util.concurrent.Executors;      
  14. /**      
  15. * 文件下载客户端      
  16. * @author tenyears.cn     
  17. */     
  18. public class NIOClient {      
  19. static int SIZE = 100;      
  20. static InetSocketAddress ip = new InetSocketAddress("localhost",12345);      
  21. static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();     
  22. static class Download implements Runnable {      
  23. protected int index;      
  24. public Download(int index) {      
  25. this.index = index;      
  26. }      
  27. public void run() {      
  28. try {      
  29. long start = System.currentTimeMillis();      
  30. SocketChannel client = SocketChannel.open();     
  31. client.configureBlocking(false);     
  32. Selector selector = Selector.open();      
  33. client.register(selector, SelectionKey.OP_CONNECT);      
  34. client.connect(ip);     
  35. ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);     
  36. int total = 0;     
  37. FOR: for (;;) {      
  38. selector.select();      
  39. Iterator iter = selector.selectedKeys()      
  40. .iterator();      
  41. while (iter.hasNext()) {      
  42. SelectionKey key = iter.next();     
  43. iter.remove();     
  44. if (key.isConnectable()) {     
  45. SocketChannel channel = (SocketChannel) key     
  46. .channel();      
  47. if (channel.isConnectionPending())     
  48. channel.finishConnect();     
  49. channel.write(encoder.encode(CharBuffer     
  50. .wrap("Hello from " + index)));     
  51. channel.register(selector, SelectionKey.OP_READ);      
  52. else if (key.isReadable()) {      
  53. SocketChannel channel = (SocketChannel) key      
  54. .channel();     
  55. int count = channel.read(buffer);     
  56. if (count > 0) {      
  57. total += count;      
  58. buffer.clear();     
  59. else {      
  60. client.close();      
  61. break FOR;      
  62. }      
  63. }     
  64. }      
  65. }      
  66. double last = (System.currentTimeMillis() - start) * 1.0 / 1000;     
  67. System.out.println("Thread " + index + " downloaded " + total      
  68. "bytes in " + last + "s.");      
  69. catch (IOException e) {      
  70. e.printStackTrace();      
  71. }      
  72. }     
  73. }     
  74. public static void main(String[] args) throws IOException {     
  75. ExecutorService exec = Executors.newFixedThreadPool(SIZE);      
  76. for (int index = 0; index < SIZE; index++) {     
  77. exec.execute(new Download(index));      
  78. }      
  79. exec.shutdown();     
  80. }      
  81. }   

操作系统的API epoll, select, NonBlocking的IO就是对select(Unix平台下)以及 WaitForMultipleObjects(Windows平台)的封装,是OS级别下的支持。

责任编辑:金贺 来源: JavaEye博客
相关推荐

2009-12-14 10:44:51

Java 7NIO2

2019-07-31 14:36:46

Linux服务器框架

2009-11-17 14:05:57

微软高性能计算服务器

2009-02-18 12:45:00

2010-05-07 17:50:31

Unix服务器

2024-03-20 08:00:00

软件开发Java编程语言

2021-09-22 16:25:17

服务器戴尔科技集团

2011-04-07 13:39:24

WebHTTP

2014-04-09 10:50:01

Squid架构缓存服务器

2011-12-08 10:12:34

JavaNIO

2019-01-08 13:32:38

Nginx服务器IO复用

2020-11-10 07:46:09

服务器高并发高性能

2018-01-12 14:37:34

Java代码实践

2021-09-14 10:21:13

CPU高性能服务器

2023-07-12 08:24:19

Java NIO通道

2019-01-15 10:54:03

高性能ServerReactor

2017-12-20 14:59:44

服务器

2021-05-28 05:18:08

PHP语言roadrunnner

2011-12-08 09:37:36

JavaNIO

2014-11-25 10:03:42

JavaScript
点赞
收藏

51CTO技术栈公众号