I/O( INPUT OUTPUT),包括文件I/O、網(wǎng)絡(luò)I/O。
計(jì)算機(jī)世界里的速度鄙視:
- 內(nèi)存讀數(shù)據(jù):納秒級(jí)別。
- 千兆網(wǎng)卡讀數(shù)據(jù): 微妙級(jí)別。 1微 秒 =1000納秒,網(wǎng)卡比內(nèi)存慢了千倍。
- 磁盤讀數(shù)據(jù):毫秒級(jí)別。1毫秒=10萬納秒 ,硬盤比內(nèi)存慢了10萬倍。
- CPU一個(gè)時(shí)鐘周期1納秒上下,內(nèi)存算是比較接近CPU的,其他都等不起。
CPU 處理數(shù)據(jù)的速度遠(yuǎn)大于I/O準(zhǔn)備數(shù)據(jù)的速度 。
任何編程語言都會(huì)遇到這種CPU處理速度和I/O速度不匹配的問題!
在網(wǎng)絡(luò)編程中如何進(jìn)行網(wǎng)絡(luò)I/O優(yōu)化: 怎么高效地利用CPU進(jìn)行網(wǎng)絡(luò)數(shù)據(jù)處理? ? ?
01
相關(guān)概念
從操作系統(tǒng)層面怎么理解網(wǎng)絡(luò)I/O呢? 計(jì)算機(jī)的世界有一套自己定義的概念。如果不明白這些概念,就無法真正明白技術(shù)的設(shè)計(jì)思路和本質(zhì)。所以在我看來,這些概念是了解技術(shù)和計(jì)算機(jī)世界的基礎(chǔ)。
1.1 同步與異步,阻塞與非阻塞
理解網(wǎng)絡(luò)I/O避不開的話題:同步與異步,阻塞與非阻塞。
拿山治燒水舉例來說,(山治的行為好比用戶程序,燒水好比內(nèi)核提供的系統(tǒng)調(diào)用),這兩組概念翻譯成大白話可以這么理解。
- 同步/異步關(guān)注的是水燒開之后需不需要我來處理。
- 阻塞/非阻塞關(guān)注的是在水燒開的這段時(shí)間是不是干了其他事。
1.1.1 同步阻塞
點(diǎn)火后,傻等,不等到水開堅(jiān)決不干任何事(阻塞),水開了關(guān)火(同步)。
1.1.2 同步非阻塞
點(diǎn)火后,去看電視(非阻塞),時(shí)不時(shí)看水開了沒有,水開后關(guān)火(同步)。
1.1.3 異步阻塞
按下開關(guān)后,傻等水開(阻塞),水開后自動(dòng)斷電(異步)。
網(wǎng)絡(luò)編程中不存在的模型。
1.1.4 異步非阻塞
按下開關(guān)后,該干嘛干嘛 (非阻塞),水開后自動(dòng)斷電(異步)。
1.2 內(nèi)核空間 、用戶空間
- 內(nèi)核負(fù)責(zé)網(wǎng)絡(luò)和文件數(shù)據(jù)的讀寫。
- 用戶程序通過系統(tǒng)調(diào)用獲得網(wǎng)絡(luò)和文件的數(shù)據(jù)。
1.2.1 內(nèi)核態(tài) 用戶態(tài)
- 程序?yàn)樽x寫數(shù)據(jù)不得不發(fā)生系統(tǒng)調(diào)用。
- 通過系統(tǒng)調(diào)用接口,線程從用戶態(tài)切換到內(nèi)核態(tài),內(nèi)核讀寫數(shù)據(jù)后,再切換回來。
- 進(jìn)程或線程的不同空間狀態(tài)。
1.2.2 線程的切換
用戶態(tài)和內(nèi)核態(tài)的切換耗時(shí),費(fèi)資源(內(nèi)存、CPU)
優(yōu)化建議:
- 更少的切換。
- 共享空間。
1.3 套接字 – socket
- 有了套接字,才可以進(jìn)行網(wǎng)絡(luò)編程。
- 應(yīng)用程序通過系統(tǒng)調(diào)用socket(),建立連接,接收和發(fā)送數(shù)據(jù)(I / O)。
- SOCKET 支持了非阻塞,應(yīng)用程序才能非阻塞調(diào)用,支持了異步,應(yīng)用程序才能異步調(diào)用
1.4 文件描述符 –FD 句柄
網(wǎng)絡(luò)編程都需要知道FD? ??FD是個(gè)什么鬼???
linux:萬物都是文件,F(xiàn)D就是文件的引用。像不像JAVA中萬物都是對(duì)象?程序中操作的是對(duì)象的引用。JAVA中創(chuàng)建對(duì)象的個(gè)數(shù)有內(nèi)存的限制,同樣FD的個(gè)數(shù)也是有限制的。
Linux在處理文件和網(wǎng)絡(luò)連接時(shí),都需要打開和關(guān)閉FD。
每個(gè)進(jìn)程都會(huì)有默認(rèn)的FD:
- 0 標(biāo)準(zhǔn)輸入 stdin
- 1 標(biāo)準(zhǔn)輸出 stdout
- 2 錯(cuò)誤輸出 stderr
1.5 服務(wù)端處理網(wǎng)絡(luò)請(qǐng)求的過程
- 連接建立后。
- 等待數(shù)據(jù)準(zhǔn)備好(CPU 閑置)。
- 將數(shù)據(jù)從內(nèi)核拷貝到進(jìn)程中(CPU閑置)。
怎么優(yōu)化呢?
對(duì)于一次I/O訪問(以read舉例),數(shù)據(jù)會(huì)先被拷貝到操作系統(tǒng)內(nèi)核的緩沖區(qū),然后才會(huì)從操作系統(tǒng)內(nèi)核的緩沖區(qū)拷貝到應(yīng)用程序的地址空間。
所以說,當(dāng)一個(gè)read操作發(fā)生時(shí),它會(huì)經(jīng)歷兩個(gè)階段:
- 等待數(shù)據(jù)準(zhǔn)備 (Waiting for the data to be ready)。
- 將數(shù)據(jù)從內(nèi)核拷貝到進(jìn)程中 (Copying the data from the kernel to the process)。
正是因?yàn)檫@兩個(gè)階段,Linux系統(tǒng)升級(jí)迭代中出現(xiàn)了下面三種網(wǎng)絡(luò)模式的解決方案。
02
I/O模型
2.1 阻塞 I/O - Blocking I/O
簡(jiǎn)介:最原始的網(wǎng)絡(luò)I/O模型。進(jìn)程會(huì)一直阻塞,直到數(shù)據(jù)拷貝完成。
缺點(diǎn):高并發(fā)時(shí),服務(wù)端與客戶端對(duì)等連接,線程多帶來的問題:
- CPU資源浪費(fèi),上下文切換。
- 內(nèi)存成本幾何上升,JVM一個(gè)線程的成本約1MB。
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress(Constant.HOST, Constant.PORT));
int idx =0;
while (true) {
final Socket socket = ss.accept();//阻塞方法
new Thread(() -> {
handle(socket);
},"線程["+idx+"]" ).start();
}
}
static void handle(Socket socket) {
byte[] bytes = new byte[1024];
try {
String serverMsg = " server sss[ 線程:"+ Thread.currentThread().getName() +"]";
socket.getOutputStream().write(serverMsg.getBytes());//阻塞方法
socket.getOutputStream().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
2.2 非阻塞 I/O - Non Blocking IO
簡(jiǎn)介: 進(jìn)程反復(fù)系統(tǒng)調(diào)用,并馬上返回結(jié)果。
缺點(diǎn): 當(dāng)進(jìn)程有1000fds,代表用戶進(jìn)程輪詢發(fā)生系統(tǒng)調(diào)用1000次kernel,來回的用戶態(tài)和內(nèi)核態(tài)的切換,成本幾何上升。
public static void main(String[] args) throws IOException {
ServerSocketChannel ss = ServerSocketChannel.open();
ss.bind(new InetSocketAddress(Constant.HOST, Constant.PORT));
System.out.println(" NIO server started ... ");
ss.configureBlocking(false);
int idx =0;
while (true) {
final SocketChannel socket = ss.accept();//阻塞方法
new Thread(() -> {
handle(socket);
},"線程["+idx+"]" ).start();
}
}
static void handle(SocketChannel socket) {
try {
socket.configureBlocking(false);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
socket.read(byteBuffer);
byteBuffer.flip();
System.out.println("請(qǐng)求:" + new String(byteBuffer.array()));
String resp = "服務(wù)器響應(yīng)";
byteBuffer.get(resp.getBytes());
socket.write(byteBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
2.3 I/O 多路復(fù)用 - IO multiplexing
簡(jiǎn)介: 單個(gè)線程就可以同時(shí)處理多個(gè)網(wǎng)絡(luò)連接。 內(nèi)核負(fù)責(zé)輪詢所有socket,當(dāng)某個(gè)socket有數(shù)據(jù)到達(dá)了,就通知用戶進(jìn)程。 多路復(fù)用在Linux內(nèi)核代碼迭代過程中依次支持了三種調(diào)用,即SELECT、POLL、EPOLL三種多路復(fù)用的網(wǎng)絡(luò)I/O模型。 下文將畫圖結(jié)合Java代碼解釋。
2.3.1 I/O 多路復(fù)用- select
簡(jiǎn)介: 有連接請(qǐng)求抵達(dá)了再檢查處理。
缺點(diǎn):
- 句柄上限- 默認(rèn)打開的FD有限制,1024個(gè)。
- 重復(fù)初始化-每次調(diào)用 select(),需要把 fd 集合從用戶態(tài)拷貝到內(nèi)核態(tài),內(nèi)核進(jìn)行遍歷。
- 逐個(gè)排查所有FD狀態(tài)效率不高。
服務(wù)端的select 就像一塊布滿插口的插排,client端的連接連上其中一個(gè)插口,建立了一個(gè)通道,然后再在通道依次注冊(cè)讀寫事件。 一個(gè)就緒、讀或?qū)懯录幚頃r(shí)一定記得刪除,要不下次還能處理。
public static void main(String[] args) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open();//管道型ServerSocket
ssc.socket().bind(new InetSocketAddress(Constant.HOST, Constant.PORT));
ssc.configureBlocking(false);//設(shè)置非阻塞
System.out.println(" NIO single server started, listening on :" + ssc.getLocalAddress());
Selector selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);//在建立好的管道上,注冊(cè)關(guān)心的事件 就緒
while(true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
while(it.hasNext()) {
SelectionKey key = it.next();
it.remove();//處理的事件,必須刪除
handle(key);
}
}
}
private static void handle(SelectionKey key) throws IOException {
if(key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);//設(shè)置非阻塞
sc.register(key.selector(), SelectionKey.OP_READ );//在建立好的管道上,注冊(cè)關(guān)心的事件 可讀
} else if (key.isReadable()) { //flip
SocketChannel sc = null;
sc = (SocketChannel)key.channel();
ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.clear();
int len = sc.read(buffer);
if(len != -1) {
System.out.println("[" +Thread.currentThread().getName()+"] recv :"+ new String(buffer.array(), 0, len));
}
ByteBuffer bufferToWrite = ByteBuffer.wrap("HelloClient".getBytes());
sc.write(bufferToWrite);
}
}
2.3.2 I/O 多路復(fù)用 – poll
簡(jiǎn)介: 設(shè)計(jì)新的數(shù)據(jù)結(jié)構(gòu)(鏈表)提供使用效率。
poll和select相比在本質(zhì)上變化不大,只是poll沒有了select方式的最大文件描述符數(shù)量的限制。
缺點(diǎn): 逐個(gè)排查所有FD狀態(tài)效率不高。
2.3.3 I/O 多路復(fù)用- epoll
簡(jiǎn)介: 沒有fd個(gè)數(shù)限制,用戶態(tài)拷貝到內(nèi)核態(tài)只需要一次,使用事件通知機(jī)制來觸發(fā)。 通過epoll_ctl注冊(cè)fd,一旦fd就緒就會(huì)通過callback回調(diào)機(jī)制來激活對(duì)應(yīng)fd,進(jìn)行相關(guān)的I/O操作。
缺點(diǎn):
- 跨平臺(tái),Linux 支持最好。
- 底層實(shí)現(xiàn)復(fù)雜。
- 同步。
public static void main(String[] args) throws Exception {
final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open()
.bind(new InetSocketAddress(Constant.HOST, Constant.PORT));
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(final AsynchronousSocketChannel client, Object attachment) {
serverChannel.accept(null, this);
ByteBuffer buffer = ByteBuffer.allocate(1024);
client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
client.write(ByteBuffer.wrap("HelloClient".getBytes()));//業(yè)務(wù)邏輯
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
System.out.println(exc.getMessage());//失敗處理
}
});
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();//失敗處理
}
});
while (true) {
//不while true main方法一瞬間結(jié)束
}
}
當(dāng)然上面的缺點(diǎn)相比較它優(yōu)點(diǎn)都可以忽略。 JDK提供了異步方式實(shí)現(xiàn),但在實(shí)際的Linux環(huán)境中底層還是epoll,只不過多了一層循環(huán),不算真正的異步非阻塞。 而且就像上圖中代碼調(diào)用,處理網(wǎng)絡(luò)連接的代碼和業(yè)務(wù)代碼解耦得不夠好。 Netty提供了簡(jiǎn)潔、解耦、結(jié)構(gòu)清晰的API。
public static void main(String[] args) {
new NettyServer().serverStart();
System.out.println("Netty server started !");
}
public void serverStart() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NIOServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new Handler());
}
});
try {
ChannelFuture f = b.localAddress(Constant.HOST, Constant.PORT).bind().sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
class Handler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
ctx.writeAndFlush(msg);
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
bossGroup 處理網(wǎng)絡(luò)請(qǐng)求的大管家(們),網(wǎng)絡(luò)連接就緒時(shí),交給workGroup干活的工人(們)。
03
總結(jié)
回顧
- 同步/異步,連接建立后,用戶程序讀寫時(shí),如果最終還是需要用戶程序來調(diào)用系統(tǒng)read()來讀數(shù)據(jù),那就是同步的,反之是異步。 windows實(shí)現(xiàn)了真正的異步,內(nèi)核代碼甚為復(fù)雜,但對(duì)用戶程序來說是透明的。
- 阻塞/非阻塞,連接建立后,用戶程序在等待可讀可寫時(shí),是不是可以干別的事兒。 如果可以就是非阻塞,反之阻塞。 大多數(shù)操作系統(tǒng)都支持的。
redis,Nginx,Netty,Node.js 為什么這么香?
這些技術(shù)都是伴隨Linux內(nèi)核迭代中提供了高效處理網(wǎng)絡(luò)請(qǐng)求的系統(tǒng)調(diào)用而出現(xiàn)的。 了解計(jì)算機(jī)底層的知識(shí)才能更深刻地理解I/O,知其然,更要知其所以然。
最后
覺得不錯(cuò)的朋友希望請(qǐng)持續(xù)關(guān)注我哦,每周定期會(huì)分享3到4篇精選干貨!






