IO线程模型
首先我们看Chat-GPT是怎么解释的:
简单来说就是IO模型就是说用什么样的通道进行数据的发送和接收,Java支持3种网络编程IO模式:BIO,NIO,AIO
BIO(Blocking IO)
同步阻塞模型,简单说一个客户端连接对应一个处理线程
BIO Java代码示例:
SocketServer服务端示例:
public class SocketServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8989);
while (true) {
System.out.println("等待连接->");
//阻塞方法
Socket clientSocket = serverSocket.accept();
System.out.println("客户端连接->");
handler(clientSocket);
/*new Thread(new Runnable() {
@Override
public void run() {
try {
handler(clientSocket);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();*/
}
}
private static void handler(Socket clientSocket) throws IOException {
byte[] bytes = new byte[1024];
System.out.println("等待read->");
//接收客户端的数据,阻塞方法,没有数据可读时阻塞
int read = clientSocket.getInputStream().read(bytes);
System.out.println("read完成->");
if (read != -1) {
System.out.println("接收客户端数据:" + new String(bytes, 0, read));
}
clientSocket.getOutputStream().write("HelloClient".getBytes());
clientSocket.getOutputStream().flush();
}
}
Socket客户端示例:
public class SocketClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8989);
//向服务端发送数据
socket.getOutputStream().write("HelloServer".getBytes());
socket.getOutputStream().flush();
System.out.println("向服务端发送数据结束-->");
byte[] bytes = new byte[1024];
//接收服务端回传的数据
socket.getInputStream().read(bytes);
System.out.println("接收到服务端的数据:" + new String(bytes));
socket.close();
}
}
应用场景:
BIO 方式适用于连接数目比较小且固定的架构, 这种方式对服务器资源要求比较高, 但程序简单易理解。
缺点:
1、代码中read操作是阻塞操作,如果连接没有数据读写操作会导致线程阻塞,浪费线程资源
2、如果线程很多,会导致服务器线程太多,CPU压力太大,比如C10K问题
NIO(Non Blocking IO)
同步非阻塞:
服务器实现模式为一个线程可以处理多个连接,客户端发送的连接请求都会注册到多路复用器selector上,多路复用器轮询到连接有IO请求就进行处理,JDK1.4引入。
应用场景:
NIO方式适用于连接数目多且连接比较短的架构, 比如IM聊天服务器, 弹幕, 服务器间通讯。
NIO非阻塞代码示例:
public class NioServer {
// 保存客户端连接
public static List<SocketChannel> channelList = new ArrayList<>();
public static void main(String[] args) throws IOException, InterruptedException {
// 创建NIO ServerSocketChannel,与BIO的serverSocket类似
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(8989));
// 设置ServerSocketChannel为非阻塞
serverSocket.configureBlocking(false);
System.out.println("服务启动成功-->");
while (true) {
// 非阻塞模式accept方法不会阻塞,反之会阻塞
// NIO的非阻塞是由操作系统内部实现的,底层调用了linux内核的accept函数
SocketChannel socketChannel = serverSocket.accept();
if (socketChannel != null) {
// 有客户端进行连接
System.out.println("连接成功->");
// 设置SocketChannel为非阻塞
socketChannel.configureBlocking(false);
// 保存客户端连接在List中
channelList.add(socketChannel);
}
// 遍历连接进行数据读取
Iterator<SocketChannel> iterator = channelList.iterator();
while (iterator.hasNext()) {
SocketChannel sc = iterator.next();
ByteBuffer byteBuffer = ByteBuffer.allocate(128);
// 非阻塞模式read方法不会阻塞,反之会阻塞
int len = sc.read(byteBuffer);
// 如果有数据
if (len > 0) {
System.out.println("接收消息:" + new String(byteBuffer.array()));
} else if (len == -1) {
//客户端断开,把socket从集合中去掉
iterator.remove();
System.out.println("客户端连接断开-->");
}
}
}
}
}
这种非阻塞代码缺点:
如果系统有过多连接,会导致大量无效遍历。例如,假设系统中有10,0000个连接,但只有1,0000个正在传输数据,每次轮询时仍然要检查所有10,0000个连接。结果,90%的轮询是无效的,这显然降低了效率。所以引入了多路复用器。
NIO引入多路复用器代码示例:
public class NioSelectorServer {
public static void main(String[] args) throws IOException, InterruptedException {
// 创建NIO ServerSocketChannel
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(8989));
// 设置ServerSocketChannel为非阻塞
serverSocket.configureBlocking(false);
// 打开Selector处理Channel,即创建epoll
Selector selector = Selector.open();
// 把ServerSocketChannel注册到selector上,并且selector对客户端accept连接操作感兴趣
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("服务启动-->");
while (true) {
// 阻塞等待需要处理的事件发生
selector.select();
// 获取selector中注册的全部事件的 SelectionKey 实例
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
// 遍历SelectionKey->对事件进行处理
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
// 如果是OP_ACCEPT事件,则进行连接获取和事件注册
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = server.accept();
socketChannel.configureBlocking(false);
// 这里只注册了读事件,如果需要给客户端发送数据可以注册写事件
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("客户端连接成功-->");
} else if (key.isReadable()) {
// 如果是OP_READ事件,则进行读取和打印
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(128);
int len = socketChannel.read(byteBuffer);
if (len > 0) {
System.out.println("接收消息:" + new String(byteBuffer.array()));
} else if (len == -1) {
// 客户端断开连接,关闭Socket
System.out.println("客户端断开连接-->");
socketChannel.close();
}
}
//从事件集合里删除本次处理的key,防止下次select重复处理
iterator.remove();
}
}
}
}
NIO 三大核心组件:
Channel(通道), Buffer(缓冲区),Selector(多路复用器)
1、channel 类似于流,每个 channel 对应一个 buffer缓冲区,buffer 底层就是个数组
2、channel 会注册到 selector 上,由 selector 根据 channel 读写事件的发生将其交由某个空闲的线程处理
3、NIO 的 Buffer 和 channel 都是既可以读也可以写
NIO底层在JDK1.4版本是用linux的内核函数select()或poll()来实现,跟上面的NioServer代码类似,selector每次都会轮询所有的sockchannel看下哪个channel有读写事件,有的话就处理,没有就继续遍历,JDK1.5开始引入了epoll基于事件响应机制来优化NIO。
Windows不支持epoll实现,windows底层是基于winsock2的select函数实现的(不开源)。
Epoll函数详解:
int epoll_create(int size);
创建一个epoll实例,并返回一个非负数作为文件描述符,用于对epoll接口的所有后续调用。参数size代表可能会容纳size个描述符,但size不是一个最大值,只是提示操作系统它的数量级,现在这个参数基本上已经弃用了。
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
使用文件描述符epfd引用的epoll实例,对目标文件描述符fd执行op操作。
参数epfd表示epoll对应的文件描述符,参数fd表示socket对应的文件描述符。
参数op有以下几个值:
EPOLL_CTL_ADD:注册新的fd到epfd中,并关联事件event;
EPOLL_CTL_MOD:修改已经注册的fd的监听事件;
EPOLL_CTL_DEL:从epfd中移除fd,并且忽略掉绑定的event,这时event可以为null;
参数event是个结构体:
struct epoll_event {
__uint32_t events; /* Epoll events */
epoll_data_t data; /* User data variable */
};
typedef union epoll_data {
void *ptr;
int fd;
__uint32_t u32;
__uint64_t u64;
} epoll_data_t;
events有很多选值,常见的几个:
EPOLLIN :表示对应的文件描述符是可读的;
EPOLLOUT:表示对应的文件描述符是可写的;
EPOLLERR:表示对应的文件描述符发生了错误;
成功则返回0,失败返回-1
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
等待文件描述符epfd上的事件。
epfd是Epoll对应的文件描述符,events表示调用者所有可用事件的集合,maxevents表示最多等到多少个事件就返回,timeout是超时时间。
NioSelectorServer核心方法:
//创建多路复用器
Selector.open()
//阻塞等待需要处理的事件发生
selector.select()
//将channel注册到多路复用器上
socketChannel.register(selector, SelectionKey.OP_READ)
总结:
NIO调用流程是通过操作系统内核函数来实现的。Java创建Socket后,获取该Socket的文件描述符,然后创建一个Selector对象。该Selector对象对应于操作系统中的Epoll描述符。接着,将Socket的文件描述符与Selector中的Epoll描述符关联,允许系统内核异步通知事件。这样,一条线程就可以高效地处理多个事件,而无需无效遍历。事件处理交由操作系统内核来管理,大大提高了效率。
Redis/Nginx线程模型:
Redis/nginx就是典型的基于epoll的NIO线程模型,epoll实例收集所有事件(连接与读写事件),由一个服务端线程连续处理所有事件命令。
AIO(NIO 2.0)
异步非阻塞, 由操作系统完成后回调通知服务端程序启动线程去处理, 一般适用于连接数较多且连接时间较长的应用。
应用场景:
AIO方式适用于连接数目多且连接比较长(重操作)的架构,JDK7 开始支持。
AIO代码示例:
public class AIOServer {
public static void main(String[] args) throws Exception {
final AsynchronousServerSocketChannel serverChannel =
AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8989));
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
try {
System.out.println("2--"+Thread.currentThread().getName());
// 再次接收客户端连接,如果不写这行代码后面的客户端连接连不上服务端
serverChannel.accept(attachment, this);
System.out.println(socketChannel.getRemoteAddress());
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer buffer) {
System.out.println("--->"+Thread.currentThread().getName());
buffer.flip();
System.out.println(new String(buffer.array(), 0, result));
socketChannel.write(ByteBuffer.wrap("HelloClient".getBytes()));
}
@Override
public void failed(Throwable exc, ByteBuffer buffer) {
exc.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
System.out.println("--->"+Thread.currentThread().getName());
Thread.sleep(Integer.MAX_VALUE);
}
}
public class AIOClient {
public static void main(String... args) throws Exception {
AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 8989)).get();
socketChannel.write(ByteBuffer.wrap("HelloServer".getBytes()));
ByteBuffer buffer = ByteBuffer.allocate(512);
Integer len = socketChannel.read(buffer).get();
if (len != -1) {
System.out.println("客户端接收信息:" + new String(buffer.array(), 0, len));
}
}
}
BIO、 NIO、 AIO 对比:
netty为什么使用NIO线程模型:
Linux系统中,AIO的底层实现仍使用Epoll,没有很好实现AIO,因此在性能上没有明显的优势,而且被JDK封装了一层不容易深度优化,因此Linux上AIO还不够成熟。
Netty是异步非阻塞框架,Netty在NIO上做了很多异步的封装。