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

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就能轻松解决这个问题。

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

 

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

 

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

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

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

 

服务器的例子:

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;

//测试文件下载的NIOServer
public class NIOServer {

	// 处理与客户端的交互
	private class HandleClient {
		protected FileChannel channel;
		protected ByteBuffer buffer;

		public HandleClient() throws IOException {
			//文件通道
			this.channel = new FileInputStream(filename).getChannel();
			//缓冲器
			this.buffer = ByteBuffer.allocate(BLOCK);
		}

		public ByteBuffer readBlock() {
			try {
				//清除缓冲,准备写
				buffer.clear();
				//注,文件是什么样的编码方式,读出来的主就是什么样的编码流
				int count = channel.read(buffer);
				//读准备
				buffer.flip();
				//读取的字节数,可能为零,如果该通道已到达流的末尾,则返回 -1 
				if (count < 0) {
					System.out.println("文件已读完...");
					//读完后关闭文件通道
					close();
					//读完后反回null
					return null;
				} else if (count == 0) {
					System.out.println("未读取到文件内容,继续...");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return buffer;
		}

		public void close() {
			try {
				//关闭文件通道
				channel.close();
				System.out.println("文件通道已关闭...");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	static int BLOCK = 1024 * 4;//块大小
	protected Selector selector;//选择器
	protected String filename = "E:\\_\\nio\\src\\pg1\\NIOServer.java"; //大文件
	protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);//
	protected CharsetDecoder decoder;//字符集解码器

	public NIOServer(int port) throws IOException {
		selector = this.getSelector(port);
		//UTF-8字符集
		Charset charset = Charset.forName("UTF-8");
		decoder = charset.newDecoder();
	}

	// 获取Selector
	protected Selector getSelector(int port) throws IOException {
		//打开服务器套接字通道
		ServerSocketChannel server = ServerSocketChannel.open();
		//打开一个选择器
		Selector sel = Selector.open();
		//把通道绑定到指定的IP与端口上
		server.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
		//调整此通道的阻塞模式为异步
		server.configureBlocking(false);
		//向指定的选择器注册此通道,感兴趣事件为套接字接受操作
		server.register(sel, SelectionKey.OP_ACCEPT);
		return sel;
	}

	// 监听端口
	public void listen() {

		while (true) {
			//已更新其准备就绪操作集的键的数目,该数目可能为零 
			try {
				if (selector.select() == 0) {
					continue;
				}
			} catch (IOException e1) {

				e1.printStackTrace();
			}
			Iterator iter = selector.selectedKeys().iterator();
			while (iter.hasNext()) {
				SelectionKey key = (SelectionKey) iter.next();
				iter.remove();//处理后删除
				try {
					handleKey(key);
				} catch (IOException e) {
					HandleClient handle = (HandleClient) key.attachment();
					if (handle != null) {
						handle.close();
					}
					key.cancel();
					e.printStackTrace();
				}
			}
		}

	}

	// 处理事件
	protected void handleKey(SelectionKey key) throws IOException {
		if (key.isAcceptable()) { // 接收请求
			doAccept(key);
		} else if (key.isReadable()) { // 读信息
			doRead(key);
		} else if (key.isWritable()) { // 写事件
			doWrite(key);
		}
	}

	private void doWrite(SelectionKey key) {
		//检索当前key的附加对象
		SocketChannel channel = (SocketChannel) key.channel();
		HandleClient handle = (HandleClient) key.attachment();
		//从大文件中读取一小块再发往客户端
		ByteBuffer block = handle.readBlock();
		//如果读到了数据,则发往客户端
		if (block != null) {
			try {
				if (block.limit() > 0) {
					channel.write(block);
				}
			} catch (IOException e) {
				//客户端通道出现异常,关闭客户端通道
				try {
					channel.close();
					System.out.println("客户羰通道异常,通道关闭...");
					handle.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		} else {//如果数据读完			
			try {
				//handle.close();
				//读完文件后关闭所对应的客户端通道
				channel.close();
				System.out.println("文件读完,客户端通道关闭...");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void doRead(SelectionKey key) throws IOException, CharacterCodingException,
			ClosedChannelException {
		SocketChannel channel = (SocketChannel) key.channel();

		//读取的字节数,可能为零,如果该通道已到达流的末尾,则返回 -1 
		int count = channel.read(clientBuffer);
		//如果读到数据
		if (count > 0) {
			//准备读
			clientBuffer.flip();
			//使用字符解码器解码缓冲中的字节内容
			CharBuffer charBuffer = decoder.decode(clientBuffer);
			System.out.println("Client >>" + charBuffer.toString());

			//读到客户端内容后,注册可写事件,后面可以向客户端写数据
			SelectionKey wKey = channel.register(selector, SelectionKey.OP_WRITE);
			//将给定的对象附加到此键。 之后可通过 attachment 方法检索已附加的对象。一次只能附加一个对象;
			//调用此方法会导致丢弃所有以前的附加对象。通过附加 null 可丢弃当前的附加对象。
			wKey.attach(new HandleClient());

		} else if (count < 0) {
			channel.close();
			System.out.println("读取客户端数据异常,通道关闭...");
		} else {
			System.out.println("未读取到数据...");
		}
		clientBuffer.clear();
	}

	private void doAccept(SelectionKey key) throws IOException, ClosedChannelException {
		ServerSocketChannel server = (ServerSocketChannel) key.channel();

		//接收新连接的套接字通道,或者如果此通道处于非阻塞模式并且没有要接受的可用连接,则返回 null 
		SocketChannel channel = server.accept();
		if (channel == null) {
			return;
		}
		System.out.println("已发现一个客户端...");
		//异步非阻塞客户端通道
		channel.configureBlocking(false);
		//准备读
		channel.register(selector, SelectionKey.OP_READ);
		//判断此通道上是否正在进行连接操作  
		if (channel.isConnectionPending()) {
			//完成套接字通道的连接过程  
			channel.finishConnect();
		}
	}

	public static void main(String[] args) {
		int port = 8088;
		try {
			NIOServer server = new NIOServer(port);
			System.out.println("Listernint on " + port);
			while (true) {
				server.listen();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

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

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;

//模拟文件下载客户端
public class NIOClient {
	static int SIZE = 100;

	//编码器
	static CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
	//解码器
	static CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();

	static class Download implements Runnable {
		protected int index;//当前线程编号

		public Download(int index) {
			this.index = index;
		}

		public void run() {
			try {
				long start = System.currentTimeMillis();
				//打开一个套接字通道
				SocketChannel client = SocketChannel.open();
				//通道使用非阻塞模式
				client.configureBlocking(false);
				// 打开一个选择器
				Selector selector = Selector.open();
				//注册与服务器连接上的事件
				client.register(selector, SelectionKey.OP_CONNECT);
				//连接此通道的套接字
				client.connect(new InetSocketAddress(InetAddress.getLocalHost(), 8088));
				//这里我们分三次才能读完服务器每次发过来的包
				ByteBuffer buffer = ByteBuffer.allocate(40);
				//接收服务器发过来的文件二进制内容,要全部接收到后解码,不然会出现乱码
				byte[] fileContentBin = new byte[1024*1024*2];
				int total = 0;
				boolean flag = true;

				while (flag) {
					//已更新其准备就绪操作集的键的数目,该数目可能为零 
					if (selector.select() == 0) {
						continue;
					}

					Iterator iter = selector.selectedKeys().iterator();
					while (iter.hasNext()) {
						SelectionKey key = (SelectionKey) iter.next();
						iter.remove();
						SocketChannel channel = (SocketChannel) key.channel();
						if (key.isConnectable()) {//如果连上了服务器

							//判断此通道上是否正在进行连接操作
							if (channel.isConnectionPending()) {
								//完成套接字通道的连接过程
								//channel.finishConnect();
							}
							//与服务器连接上后向服务器发UTF-8的送消息,这里要注意的是,我们只需向服务器端发送一次
							//消息,所以这里就直接发送了,而没有采用注册感兴趣的事件机制
							channel.write(encoder.encode(CharBuffer.wrap("你好 from " + index)));
							//关注此通道上的可读写操作  
							channel
									.register(selector, SelectionKey.OP_READ
											| SelectionKey.OP_WRITE);
						} else if (key.isReadable()) {//通道上有数据可读时
							//读取的字节数,可能为零,如果该通道已到达流的末尾,则返回 -1 
							int count = channel.read(buffer);

							while (count > 0) {
								//System.out.println("count1===" + count);
								buffer.flip();
								buffer.get(fileContentBin, total, count);
								total += count;

								buffer.clear();
								count = channel.read(buffer);
							}
							//System.out.println("count2===" + count);
							if (count == -1) {
								System.out.println("通道异常,关闭...");
								client.close();
								flag = false; //此处flag为最外面的for循环的终止标记
							}
							if (count == 0) {
								//System.out.println("未读到内容,继续...");
							}
						} else if (key.isWritable()) {//可以向通道写数据时  
							//与服务器连接上后向服务器发UTF-8的送消息,
							channel.write(encoder.encode(CharBuffer.wrap("你好 from " + index)));
							//发送信息后去掉写事件
							key.interestOps(SelectionKey.OP_READ);
						}
					}
				}
				try {
					OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(new File(
							"e:/tmp/" + this.index + ".txt")), "UTF-8");
					//注:这里一定要等文件读完后解码,不然会出现异常,因为这是从网络流中读取的,可能一个字符的编码还没有补完全传过来,所以最
					//好等文件全传过来后一起解码,当然也可以读一部分解一部分,但要判断是否是完整的流,较烦
					ow.write(decoder.decode(ByteBuffer.wrap(fileContentBin, 0, total)).toString());
					ow.close();
				} catch (CharacterCodingException e) {
					e.printStackTrace();
				}

				double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
				System.out.println("Thread " + index + " downloaded " + total + "bytes in " + last
						+ "s.");

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException {

		for (int index = 0; index < SIZE; index++) {

			new Thread(new Download(index)).start();
		}
	}
}

 

你可能感兴趣的:(java,多线程,tomcat,.net,socket)