文章插圖

文章插圖
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 同步阻塞
點火后,傻等,不等到水開堅決不干任何事(阻塞),水開了關火(同步) 。
點火后,去看電視(非阻塞),時不時看水開了沒有,水開后關火(同步) 。
按下開關后,傻等水開(阻塞),水開后自動斷電(異步) 。
1.1.4 異步非阻塞
按下開關后,該干嘛干嘛 (非阻塞),水開后自動斷電(異步) 。
優化建議:
更少的切換 。共享空間 。1.3 套接字 – socket
Linux:萬物都是文件,FD就是文件的引用 。像不像JAVA中萬物都是對象?程序中操作的是對象的引用 。JAVA中創建對象的個數有內存的限制,同樣FD的個數也是有限制的 。
每個進程都會有默認的FD:
0 標準輸入 stdin1 標準輸出 stdout2 錯誤輸出 stderr1.5 服務端處理網絡請求的過程
怎么優化呢?
對于一次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
缺點:高并發時,服務端與客戶端對等連接,線程多帶來的問題:
CPU資源浪費,上下文切換 。內存成本幾何上升,JVM一個線程的成本約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缺點:當進程有1000fds,代表用戶進程輪詢發生系統調用1000次kernel,來回的用戶態和內核態的切換,成本幾何上升 。
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();}}2.3 I/O 多路復用 – IO multiplexing2.3.1 I/O 多路復用- select
缺點:
句柄上限- 默認打開的FD有限制,1024個 。重復初始化-每次調用 select(),需要把 fd 集合從用戶態拷貝到內核態,內核進行遍歷 。逐個排查所有FD狀態效率不高 。
服務端的select 就像一塊布滿插口的插排,client端的連接連上其中一個插口,建立了一個通道,然后再在通道依次注冊讀寫事件 。一個就緒、讀或寫事件處理時一定記得刪除,要不下次還能處理 。
public static void main(String[] args) throws IOException {ServerSocketChannel ssc = ServerSocketChannel.open();//管道型ServerSocketssc.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<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);//設置非阻塞sc.register(key.selector(), SelectionKey.OP_READ );//在建立好的管道上,注冊關心的事件 可讀} else if (key.isReadable()) { //flipSocketChannel 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 多路復用 – pollpoll和select相比在本質上變化不大,只是poll沒有了select方式的最大文件描述符數量的限制 。
缺點:逐個排查所有FD狀態效率不高 。
2.3.3 I/O 多路復用- epoll
簡介:沒有fd個數限制,用戶態拷貝到內核態只需要一次,使用事件通知機制來觸發 。通過epoll_ctl注冊fd,一旦fd就緒就會通過callback回調機制來激活對應fd,進行相關的I/O操作 。
缺點:
跨平臺,Linux 支持最好 。底層實現復雜 。同步 。
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>() {@Overridepublic void completed(final AsynchronousSocketChannel client, Object attachment) {serverChannel.accept(null, this);ByteBuffer buffer = ByteBuffer.allocate(1024);client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {@Overridepublic void completed(Integer result, ByteBuffer attachment) {attachment.flip();client.write(ByteBuffer.wrap("HelloClient".getBytes()));//業務邏輯}@Overridepublic void failed(Throwable exc, ByteBuffer attachment) {System.out.println(exc.getMessage());//失敗處理}});}@Overridepublic void failed(Throwable exc, Object attachment) {exc.printStackTrace();//失敗處理}});while (true) {//不while true main方法一瞬間結束}}當然上面的缺點相比較它優點都可以忽略 。JDK提供了異步方式實現,但在實際的Linux環境中底層還是epoll,只不過多了一層循環,不算真正的異步非阻塞 。而且就像上圖中代碼調用,處理網絡連接的代碼和業務代碼解耦得不夠好 。Netty提供了簡潔、解耦、結構清晰的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>() {@Overrideprotected 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 {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf = (ByteBuf) msg;ctx.writeAndFlush(msg);ctx.close();}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}}bossGroup 處理網絡請求的大管家(們),網絡連接就緒時,交給workGroup干活的工人(們) 。三、總結回顧同步/異步,連接建立后,用戶程序讀寫時,如果最終還是需要用戶程序來調用系統read()來讀數據,那就是同步的,反之是異步 。Windows實現了真正的異步,內核代碼甚為復雜,但對用戶程序來說是透明的 。阻塞/非阻塞,連接建立后,用戶程序在等待可讀可寫時,是不是可以干別的事兒 。如果可以就是非阻塞,反之阻塞 。大多數操作系統都支持的 。Redis,Nginx,Netty,Node.js 為什么這么香?
【linux網絡配置命令有哪些 linux網絡配置命令實驗報告】這些技術都是伴隨Linux內核迭代中提供了高效處理網絡請求的系統調用而出現的 。了解計算機底層的知識才能更深刻地理解I/O,知其然,更要知其所以然 。與君共勉!
- mini機箱配置 Mini機箱
- linux搜索文件命令find linux搜索文件命令grep
- 手機虛擬傳真機軟件 網絡虛擬傳真機
- 關于網絡營銷的案例 網絡營銷的成功案例有哪些
- 網絡攻擊的種類有哪些?語義攻擊 網絡攻擊的種類有哪些?怎么防范
- linux打開谷歌瀏覽器命令 命令行安裝谷歌瀏覽器
- 華為mate10配置參數表 mate10配置參數詳情
- 龍卷風網絡收音機App2015版下載 龍卷風網絡收音機官網
- 蘋果官網一體機怎么看配置 蘋果一體機型號查詢
- idea怎么配置jdk環境變量 安裝idea用配置jdk環境變量嗎
