從操作系統層面理解Linux下的網絡IO模型

I/O( INPUT OUTPUT),包括文件I/O、網絡I/O。

計算機世界裡的速度鄙視:

  • 內存讀數據:納秒級別。
  • 千兆網卡讀數據:微妙級別。1微秒=1000納秒,網卡比內存慢了千倍。
  • 磁盤讀數據:毫秒級別。1毫秒=10萬納秒 ,硬盤比內存慢了10萬倍。
  • CPU一個時鐘週期1納秒上下,內存算是比較接近CPU的,其他都等不起。

CPU 處理數據的速度遠大於I/O準備數據的速度 。

任何編程語言都會遇到這種CPU處理速度和I/O速度不匹配的問題!

在網絡編程中如何進行網絡I/O優化:怎麼高效地利用CPU進行網絡數據處理???

一、相關概念

從操作系統層面怎麼理解網絡I/O呢?計算機的世界有一套自己定義的概念。如果不明白這些概念,就無法真正明白技術的設計思路和本質。所以在我看來,這些概念是瞭解技術和計算機世界的基礎。

1.1 同步與異步,阻塞與非阻塞

理解網絡I/O避不開的話題:同步與異步,阻塞與非阻塞。

拿山治燒水舉例來說,(山治的行為好比用戶程序,燒水好比內核提供的系統調用),這兩組概念翻譯成大白話可以這麼理解。

  • 同步/異步關注的是水燒開之後需不需要我來處理。
  • 阻塞/非阻塞關注的是在水燒開的這段時間是不是幹了其他事。

1.1.1 同步阻塞

點火後,傻等,不等到水開堅決不幹任何事(阻塞),水開了關火(同步)。

從操作系統層面理解Linux下的網絡IO模型

1.1.2 同步非阻塞

點火後,去看電視(非阻塞),時不時看水開了沒有,水開後關火(同步)。

從操作系統層面理解Linux下的網絡IO模型

1.1.3 異步阻塞

按下開關後,傻等水開(阻塞),水開後自動斷電(異步)。

從操作系統層面理解Linux下的網絡IO模型

網絡編程中不存在的模型。

1.1.4 異步非阻塞

按下開關後,該幹嘛幹嘛 (非阻塞),水開後自動斷電(異步)。

從操作系統層面理解Linux下的網絡IO模型

1.2 內核空間 、用戶空間

從操作系統層面理解Linux下的網絡IO模型

  • 內核負責網絡和文件數據的讀寫。
  • 用戶程序通過系統調用獲得網絡和文件的數據。

1.2.1 內核態 用戶態

從操作系統層面理解Linux下的網絡IO模型

  • 程序為讀寫數據不得不發生系統調用。
  • 通過系統調用接口,線程從用戶態切換到內核態,內核讀寫數據後,再切換回來。
  • 進程或線程的不同空間狀態。

1.2.2 線程的切換

從操作系統層面理解Linux下的網絡IO模型

用戶態和內核態的切換耗時,費資源(內存、CPU)

優化建議:

  • 更少的切換。
  • 共享空間。

1.3 套接字 – socket

從操作系統層面理解Linux下的網絡IO模型

  • 有了套接字,才可以進行網絡編程。
  • 應用程序通過系統調用socket(),建立連接,接收和發送數據(I / O)。
  • SOCKET 支持了非阻塞,應用程序才能非阻塞調用,支持了異步,應用程序才能異步調用

1.4 文件描述符 –FD 句柄

從操作系統層面理解Linux下的網絡IO模型

從操作系統層面理解Linux下的網絡IO模型

從操作系統層面理解Linux下的網絡IO模型

網絡編程都需要知道FD??? FD是個什麼鬼???

Linux:萬物都是文件,FD就是文件的引用。像不像JAVA中萬物都是對象?程序中操作的是對象的引用。JAVA中創建對象的個數有內存的限制,同樣FD的個數也是有限制的。

從操作系統層面理解Linux下的網絡IO模型

Linux在處理文件和網絡連接時,都需要打開和關閉FD。

每個進程都會有默認的FD:

  • 0 標準輸入 stdin
  • 1 標準輸出 stdout
  • 2 錯誤輸出 stderr

1.5 服務端處理網絡請求的過程

從操作系統層面理解Linux下的網絡IO模型

  • 連接建立後。
  • 等待數據準備好(CPU 閒置)。
  • 將數據從內核拷貝到進程中(CPU閒置)。

怎麼優化呢?

對於一次I/O訪問(以read舉例),數據會先被拷貝到操作系統內核的緩衝區,然後才會從操作系統內核的緩衝區拷貝到應用程序的地址空間。

所以說,當一個read操作發生時,它會經歷兩個階段:

  • 等待數據準備 (Waiting for the data to be ready)。
  • 將數據從內核拷貝到進程中 (Copying the data from the kernel to the process)。

正是因為這兩個階段,Linux系統升級迭代中出現了下面三種網絡模式的解決方案。

二、IO模型介紹

2.1 阻塞 I/O - Blocking I/O

從操作系統層面理解Linux下的網絡IO模型

簡介:最原始的網絡I/O模型。進程會一直阻塞,直到數據拷貝完成。

缺點:高併發時,服務端與客戶端對等連接,線程多帶來的問題:

  • CPU資源浪費,上下文切換。
  • 內存成本幾何上升,JVM一個線程的成本約1MB。
<code>

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(); } } /<code>

2.2 非阻塞 I/O - Non Blocking IO

從操作系統層面理解Linux下的網絡IO模型

簡介:進程反覆系統調用,並馬上返回結果。

缺點:當進程有1000fds,代表用戶進程輪詢發生系統調用1000次kernel,來回的用戶態和內核態的切換,成本幾何上升。

<code>

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(

"請求:"

+

new

String(byteBuffer.array())); String resp =

"服務器響應"

; byteBuffer.

get

(resp.getBytes()); socket.write(byteBuffer); }

catch

(IOException e) { e.printStackTrace(); } } /<code>

2.3 I/O 多路複用 - IO multiplexing

從操作系統層面理解Linux下的網絡IO模型

簡介:單個線程就可以同時處理多個網絡連接。內核負責輪詢所有socket,當某個socket有數據到達了,就通知用戶進程。多路複用在Linux內核代碼迭代過程中依次支持了三種調用,即SELECT、POLL、EPOLL三種多路複用的網絡I/O模型。下文將畫圖結合Java代碼解釋。

2.3.1 I/O 多路複用- select

從操作系統層面理解Linux下的網絡IO模型

簡介:有連接請求抵達了再檢查處理。

缺點:

  • 句柄上限- 默認打開的FD有限制,1024個。
  • 重複初始化-每次調用 select(),需要把 fd 集合從用戶態拷貝到內核態,內核進行遍歷。
  • 逐個排查所有FD狀態效率不高。

服務端的select 就像一塊佈滿插口的插排,client端的連接連上其中一個插口,建立了一個通道,然後再在通道依次註冊讀寫事件。一個就緒、讀或寫事件處理時一定記得刪除,要不下次還能處理。

<code>

public

static

void

main

(

String[] args

) throws IOException

{ ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(

new

InetSocketAddress(Constant.HOST, Constant.PORT)); ssc.configureBlocking(

false

); System.

out

.println(

" NIO single server started, listening on :"

+ ssc.getLocalAddress()); Selector selector = Selector.open(); ssc.register(selector, SelectionKey.OP_ACCEPT);

while

(

true

) { selector.

select

(); Set keys = selector.selectedKeys(); Iterator 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

); sc.register(key.selector(), SelectionKey.OP_READ ); }

else

if

(key.isReadable()) { 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); } } /<code>

2.3.2 I/O 多路複用 – poll

從操作系統層面理解Linux下的網絡IO模型

簡介:設計新的數據結構(鏈表)提供使用效率。

poll和select相比在本質上變化不大,只是poll沒有了select方式的最大文件描述符數量的限制。

缺點:逐個排查所有FD狀態效率不高。

2.3.3 I/O 多路複用- epoll

簡介:沒有fd個數限制,用戶態拷貝到內核態只需要一次,使用事件通知機制來觸發。通過epoll_ctl註冊fd,一旦fd就緒就會通過callback回調機制來激活對應fd,進行相關的I/O操作。

缺點:

  • 跨平臺,Linux 支持最好。
  • 底層實現複雜。
  • 同步。
<code> 

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() {

public

void

completed

(

final

AsynchronousSocketChannel client, Object attachment)

{ serverChannel.accept(

null

,

this

); ByteBuffer buffer = ByteBuffer.allocate(

1024

); client.read(buffer, buffer,

new

CompletionHandler() {

public

void

completed

(Integer result, ByteBuffer attachment)

{ attachment.flip(); client.write(ByteBuffer.wrap(

"HelloClient"

.getBytes())); }

public

void

failed

(Throwable exc, ByteBuffer attachment)

{ System.out.println(exc.getMessage()); } }); }

public

void

failed

(Throwable exc, Object attachment)

{ exc.printStackTrace(); } });

while

(

true

) { } } /<code>

當然上面的缺點相比較它優點都可以忽略。JDK提供了異步方式實現,但在實際的Linux環境中底層還是epoll,只不過多了一層循環,不算真正的異步非阻塞。而且就像上圖中代碼調用,處理網絡連接的代碼和業務代碼解耦得不夠好。Netty提供了簡潔、解耦、結構清晰的API。

<code> 

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

>()

{

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

{

public

void

channelRead

(ChannelHandlerContext ctx, Object msg)

throws

Exception

{ ByteBuf buf = (ByteBuf) msg; ctx.writeAndFlush(msg); ctx.close(); }

public

void

exceptionCaught

(ChannelHandlerContext ctx, Throwable cause)

throws

Exception

{ cause.printStackTrace(); ctx.close(); } } /<code>

bossGroup 處理網絡請求的大管家(們),網絡連接就緒時,交給workGroup幹活的工人(們)。

三、總結

回顧

  • 同步/異步,連接建立後,用戶程序讀寫時,如果最終還是需要用戶程序來調用系統read()來讀數據,那就是同步的,反之是異步。Windows實現了真正的異步,內核代碼甚為複雜,但對用戶程序來說是透明的。
  • 阻塞/非阻塞,連接建立後,用戶程序在等待可讀可寫時,是不是可以幹別的事兒。如果可以就是非阻塞,反之阻塞。大多數操作系統都支持的。

Redis,Nginx,Netty,Node.js 為什麼這麼香?

這些技術都是伴隨Linux內核迭代中提供了高效處理網絡請求的系統調用而出現的。瞭解計算機底層的知識才能更深刻地理解I/O,知其然,更要知其所以然。與君共勉!

原文地址:https://my.oschina.net/u/4007037/blog/3158516


專欄

Java面試通關100問

作者:Java識堂

19.9幣

257人已購

查看


分享到:


相關文章: