一文弄懂-BIO,NIO,AIO

2022-12-26,,,,

目录

一文弄懂-BIO,NIO,AIO

1. BIO: 同步阻塞IO模型

2. NIO: 同步非阻塞IO模型(多路复用)

3.Epoll函数详解

4.Redis线程模型

5. AIO: 异步非阻塞IO模型 (NIO 2.0)


1. BIO: 同步阻塞IO模型

特点:对于客户端的请求,服务端是同步返回结果的 如果服务端一直在处理中 那么这个线程就会阻塞着

缺点:1. 线程阻塞浪费很多资源

2. C10K问题:线程很多,服务器压力太大, 且没有服务器能承受10k的连接数

应用场景: 使用与连接数固定且较小的通信架构,程序简单易懂

代码示例:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; public class SocketServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9000);
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();
}
}
//客户端代码
public class SocketClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 9000);
//向服务端发送数据
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();
}
}

  



2. NIO: 同步非阻塞IO模型(多路复用)

    非阻塞的解释: 一个线程多路复用(通过linux的epoll基于事件响应机制来实现一个线程处理多个请求)

使用场景:适用于连接数多且连接比较短的架构,比如聊天服务器,弹幕系统,服务器间的通讯,编程比较复杂(后面会讲到netty解决这个问题)

   NIO非阻塞代码示例:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; public class NioServer { // 保存客户端连接
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(9000));
// 设置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("客户端断开连接");
}
}
}
}
}

  

总结:上面的示例还没有用到selector多路复用器 只是一个非阻塞IO的操作,当有10000个连接的时候,下面的while循环会循环10000次,而这时假如只有1000个连接是有数据交互的,那么9000个连接实际上并没有断开,也需要循环。所有为了解决无用连接被循环造成大量资源浪费的问题,我们需要引入多路复用器。

NIO多路复用器代码示例:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set; public class NioSelectorServer { public static void main(String[] args) throws IOException, InterruptedException { // 创建NIO ServerSocketChannel
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(9000));
// 设置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() 函数进行实现的 跟非阻塞的那个示例代码一样,每次都要遍历所有的channel

后面JDK1.4之后使用epoll()函数基于事件监听机制实现的,只会对有事件的channel进行遍历并处理事件,多路复用器selector会会将我们channel的事件放到rdlist中,然后从rdlist中取出事件进行处理

NIioSelectorServer 三个核心的方法:

Selector.open() //创建多路复用器 

socketChannel.register(selector, SelectionKey.OP_READ) //将channel注册到多路复用器上 

selector.select() //阻塞等待需要处理的事件发生

  

Selector.open() :创建多路复用器 Hotspot会根据不同的操作系统,调用调用不同系统底层创建epoll实例的函数,例如linux调用epoll_create()函数返回的是一个epfd文件描述符(linux内核为了高效管理已打开文件,为其创建的索引,就叫文件描述符,通过该索引可以找到对应的文件)

socketChannel.register(selector, SelectionKey.OP_READ):将channel及其对应的事件注册到selector

selector.select(): 将创建的epfd放入到内部的集合中,然后调用linux底层函数epoll_ctl()进行事件绑定(真正的事件注册),然后调用内核函数epoll_wait() 进行阻塞处理等待队列,如果rdlist队列中有事件,那么就直接返回,如果没有事件,就阻塞进程

总结: NIO整个调用流程就是调用操作系统内核函数来创建Socket,获取到Socket的文件描述符,然后创建一个Selector,对应操作系统中的Epoll文件描述符,将Socket文件描述符绑定到Epoll文件描述符上,进行事件的异步通知,这样就实现了使用一个线程,并且不需要太多的遍历,将事件处理交给了操作系统内核的中断事件(socket接收到数据后,往rdlist中添加socket文件符的操作就是中断程序做的)

3.Epoll函数详解

上面在讲解selector核心的三个方法的时候,其实就是对应着操作系统内核底层的epoll的三个函数:

int epoll_create(int size);

创建一个epoll示例,返回一个非负数的文件描述符,参数size可忽略,已经弃用

int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);

  

参数:epfd表示epoll示例的文件描述符

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上面的事件,events表示调用者所有可用事件的集合,maxevents表示最多等到多少个事件就返回,timeout表示超时时间

4.Redis线程模型

Redis就是典型的基于epoll的NIO线程模型(nginx也是),epoll实例收集所有事件(连接与读写事件),由一个服务端线程连续处理所有事件的命令

Redis底层关于epoll的源码实现在redis的src源码目录的ae_epoll.c文件里,感兴趣的可以看看

5. AIO: 异步非阻塞IO模型 (NIO 2.0)

应用场景:AIO方式适用于连接数目多且连接比较长得架构,jdk1.7后开始支持,但是由于编程难度大,linux底层对aio的支持不够完美,所以很少用AIO直接编程我们的系统 而是使用Netty这种优秀的中间件完成,Netty底层是对NIO的封装

AIO示例代码:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler; public class AIOServer { public static void main(String[] args) throws Exception {
final AsynchronousServerSocketChannel serverChannel =
AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(9000)); 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("3--"+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("1--"+Thread.currentThread().getName());
Thread.sleep(Integer.MAX_VALUE);
}
}


import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel; public class AIOClient { public static void main(String... args) throws Exception {
AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 9000)).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));
}
}
}

  

为什么Netty底层使用NIO而不使用AIO?

AIO底层也是Epoll,但是Epoll在异步上做的不是很好,而且经过了JDK封装,不容易深度优化,所以有了Netty,Netty是异步非阻塞IO框架,它底层对NIO做了很多异步的操作。

为了方便更好的理解 同步与异步 阻塞与非阻塞的概念 可以看下面段子:

老张爱喝茶,废话不说,煮开水。

出场人物:老张,水壶两把(普通水壶,简称水壶;会响的水壶,简称响水壶)。

1 老张把水壶放到火上,立等水开。(同步阻塞)

老张觉得自己有点傻

2 老张把水壶放到火上,去客厅看电视,时不时去厨房看看水开没有。(同步非阻塞)

老张还是觉得自己有点傻,于是变高端了,买了把会响笛的那种水壶。水开之后,能大声发出嘀~~~~的噪音。

3 老张把响水壶放到火上,立等水开。(异步阻塞)

老张觉得这样傻等意义不大

4 老张把响水壶放到火上,去客厅看电视,水壶响之前不再去看它了,响了再去拿壶。(异步非阻塞)

老张觉得自己聪明了。

所谓同步异步,只是对于水壶而言。

普通水壶,同步;响水壶,异步。

虽然都能干活,但响水壶可以在自己完工之后,提示老张水开了。这是普通水壶所不能及的。

同步只能让调用者去轮询自己(情况2中),造成老张效率的低下。

所谓阻塞非阻塞,仅仅对于老张而言。

立等的老张,阻塞;看电视的老张,非阻塞。

总结: 同步异步相当于接受消息方而言,接收方能在处理完事件后通知到请求方,那么就是异步,如果需要请求方不断轮询查看结果 那么就是同步

            阻塞非阻塞相当于请求方而言,我只能等待一个请求结束后才能干其他事 这就是阻塞 如果我发送了一个请求后立马能做其他事 这就是非阻塞

一文弄懂-BIO,NIO,AIO的相关教程结束。

《一文弄懂-BIO,NIO,AIO.doc》

下载本文的Word格式文档,以方便收藏与打印。