前言:
小弟能力不足,認知有限,難免考慮不全面,希望大佬能給出更好的建議,指出存在的問題和不足,在此跪謝。
IO發展史
Java中對于I/O能力的支持主要分為三個比較關鍵的階段:
BIO
第一個階段是起步階段JDK1.0 ~ JDK1.3,這個階段JDK是處于BIO階段的,也就是同步阻塞模式,該階段的類庫還非常的初級,對系統層面的一些網絡編程的API都沒有進行實現,因此這個階段的很多大型應用服務器都采用C或者C++語言來進行開發的,因為C或者C++可以直接調用操作系統提供的非阻塞I/O能力;
NIO
第二個階段從JDK1.4開始的,從JDK1.4開始,Java新增了java.nio的包,正式支持的NIO,提供了許多非阻塞I/O開發的API和類庫;
AIO
第三個階段是從JDK1.7開始的,這一次是對原來的NIO類庫進行了升級,官方稱為NIO 2.0,該版本不但強化了原來的基于I/O多路復用模型的NIO模式,同時新增了異步的AIO功能,所以也有很多人稱之為AIO。
各個IO介紹
BIO
在Java中,BIO(Blocking I/O)指的是阻塞式I/O,是一種基本的I/O模型。它的實現原理相對簡單,但在高并發場景下性能較差。下面我將詳細介紹BIO的實現原理。
-
阻塞式I/O:
在BIO中,當一個線程在進行I/O操作時,如果數據沒有準備好,該線程會被阻塞,直到數據準備好并被讀取或寫入。這意味著一個線程只能處理一個連接,如果有大量連接同時到來,就需要大量線程來處理,這會導致資源消耗過大。 -
實現原理:
- 服務端:服務端通過ServerSocket監聽客戶端的連接請求。當有連接請求到來時,服務端會創建一個新的線程來處理該連接。
- 客戶端:客戶端通過Socket向服務端發起連接請求。一旦連接建立,客戶端和服務端之間可以進行數據的讀取和寫入。
-
服務端示例代碼:
思路:在服務端的代碼中,我們創建了一個固定大小的線程池,用于處理客戶端的連接請求。每當有客戶端連接時,就會將連接交給線程池中的一個線程來處理,這樣可以提高并發處理能力。同時,我們定義了一個
ClientHandler
類來處理客戶端的請求,這樣可以更好地組織代碼邏輯。這樣的設計可以更好地滿足企業級生產環境的要求,提高了系統的并發處理能力和穩定性。當然你還可以加入日志打印,更好的排查問題,但是因為這種已經過時,所以只是簡單示例。
import java.io.*; import java.net.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class Server {public static void main(String[] args) {ServerSocket serverSocket = null;ExecutorService executor = Executors.newFixedThreadPool(10); // 創建一個固定大小的線程池try {serverSocket = new ServerSocket(8080);System.out.println("Server started. Waiting for client...");while (true) {// 等待客戶端連接Socket clientSocket = serverSocket.accept();System.out.println("Client connected: " + clientSocket.getRemoteSocketAddress());// 使用線程池處理客戶端請求executor.execute(new ClientHandler(clientSocket));}} catch (IOException e) {e.printStackTrace();} finally {try {if (serverSocket != null) {serverSocket.close();}executor.shutdown(); // 關閉線程池} catch (IOException e) {e.printStackTrace();}}}private static class ClientHandler implements Runnable {private Socket clientSocket;public ClientHandler(Socket clientSocket) {this.clientSocket = clientSocket;}@Overridepublic void run() {try {// 獲取輸入流BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));// 獲取輸出流PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true);// 讀取客戶端發送的數據String clientMessage = input.readLine();System.out.println("Received from client: " + clientMessage);// 向客戶端發送數據output.println("Hello, client!");// 關閉流和連接input.close();output.close();clientSocket.close();} catch (IOException e) {e.printStackTrace();}}} }
-
客戶端實例代碼實現:
import java.io.*; import java.net.*;public class Client {public static void main(String[] args) {Socket socket = null;try {socket = new Socket("localhost", 8080);System.out.println("Connected to server.");// 獲取輸入流BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));// 獲取輸出流PrintWriter output = new PrintWriter(socket.getOutputStream(), true);// 向服務端發送數據output.println("Hello, server!");// 讀取服務端發送的數據String serverMessage = input.readLine();System.out.println("Received from server: " + serverMessage);// 關閉流和連接input.close();output.close();socket.close();} catch (IOException e) {e.printStackTrace();} finally {try {if (socket != null) {socket.close();}} catch (IOException e) {e.printStackTrace();}}} }
-
適用場景:
BIO適用于連接數較少且吞吐量要求不高的場景,例如傳統的Socket通信應用。 -
局限性:
由于BIO的阻塞特性,它在高并發場景下表現較差,因為大量線程會因為I/O阻塞而處于等待狀態,導致資源浪費。
總的來說,BIO是一種簡單直觀的I/O模型,但在高并發場景下存在性能瓶頸。隨著業務的發展,通常會選擇更高效的NIO(Non-blocking I/O)或者AIO(Asynchronous I/O)來替代BIO。
NIO
在Java中,NIO(New I/O)是一種非阻塞I/O模型,相比于傳統的BIO(Blocking I/O),NIO具有更高的并發處理能力。下面我將詳細介紹NIO的實現原理。
-
非阻塞I/O:
NIO的核心是非阻塞I/O,它允許一個線程處理多個連接,當一個連接上的I/O操作不可立即完成時,線程可以去處理其他連接,而不是被阻塞。 -
核心組件:
- 通道(Channel):用于讀取和寫入數據,可以是文件、套接字等。
- 緩沖區(Buffer):用于臨時存儲數據,讀取數據到緩沖區或將緩沖區中的數據寫入通道。
- 選擇器(Selector):用于監聽多個通道的事件,例如連接就緒、讀就緒、寫就緒等。
-
實現原理:
- 服務端:服務端通過ServerSocketChannel監聽連接請求,一旦有連接到來,會將該連接注冊到Selector上,并監聽連接就緒事件。
- 客戶端:客戶端通過SocketChannel向服務端發起連接請求,連接建立后也會注冊到Selector上。
-
NIO服務器端示例代碼:
實現思路:在以下代碼中,我們引入了日志打印服務,使用了Java自帶的Logger類來記錄日志。同時,我們使用了線程池來處理客戶端的連接請求和數據讀寫操作,以提高并發處理能力。對于各種可能遇到的問題,比如連接超時、網絡異常、數據讀寫異常等,我們在相應的位置進行了異常處理,并記錄了相應的日志,以便于排查和解決問題。
這樣的設計更加符合企業級生產規范,提高了系統的并發處理能力和穩定性,并且對各種異常情況進行了處理,使得系統更加健壯可靠。
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger;public class NIOServer {private static final Logger logger = Logger.getLogger(NIOServer.class.getName());private static final ExecutorService executor = Executors.newFixedThreadPool(10);public static void main(String[] args) {try {Selector selector = Selector.open();ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.socket().bind(new InetSocketAddress(8080));serverSocketChannel.configureBlocking(false);serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {selector.select();Set<SelectionKey> selectedKeys = selector.selectedKeys();Iterator<SelectionKey> keyIterator = selectedKeys.iterator();while (keyIterator.hasNext()) {SelectionKey key = keyIterator.next();keyIterator.remove();if (key.isAcceptable()) {executor.execute(() -> handleAccept(key, selector));} else if (key.isReadable()) {executor.execute(() -> handleRead(key));}}}} catch (IOException e) {logger.severe("Error in NIO server: " + e.getMessage());}}private static void handleAccept(SelectionKey key, Selector selector) {try {ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();SocketChannel clientChannel = serverSocketChannel.accept();clientChannel.configureBlocking(false);clientChannel.register(selector, SelectionKey.OP_READ);} catch (IOException e) {logger.severe("Error in handleAccept: " + e.getMessage());}}private static void handleRead(SelectionKey key) {try {SocketChannel clientChannel = (SocketChannel) key.channel();ByteBuffer buffer = ByteBuffer.allocate(1024);int bytesRead = clientChannel.read(buffer);if (bytesRead == -1) {clientChannel.close();key.cancel();} else if (bytesRead > 0) {buffer.flip();byte[] data = new byte[bytesRead];buffer.get(data);logger.info("Received from client: " + new String(data));// 可以在這里處理接收到的數據}} catch (IOException e) {logger.severe("Error in handleRead: " + e.getMessage());}} }
-
NIO客戶端的代碼:
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger;public class NIOClient {private static final Logger logger = Logger.getLogger(NIOClient.class.getName());private static final ExecutorService executor = Executors.newFixedThreadPool(10);public static void main(String[] args) {try {SocketChannel socketChannel = SocketChannel.open();socketChannel.configureBlocking(false);socketChannel.connect(new InetSocketAddress("localhost", 8080));while (!socketChannel.finishConnect()) {// 等待連接完成}executor.execute(() -> {try {String message = "Hello, server!";ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());socketChannel.write(buffer);buffer.clear();int bytesRead = socketChannel.read(buffer);if (bytesRead > 0) {buffer.flip();byte[] data = new byte[bytesRead];buffer.get(data);logger.info("Received from server: " + new String(data));// 可以在這里處理接收到的數據}} catch (IOException e) {logger.severe("Error in NIO client: " + e.getMessage());} finally {try {socketChannel.close();} catch (IOException e) {logger.severe("Error in closing socket channel: " + e.getMessage());}}});} catch (IOException e) {logger.severe("Error in NIO client: " + e.getMessage());}} }
-
適用場景:
NIO適用于高并發的網絡應用,例如Web服務器、聊天服務器等,能夠更高效地處理大量連接。
總的來說,NIO通過Selector、Channel和Buffer的組合,實現了非阻塞I/O,提高了系統的并發處理能力。然而,NIO編程相對復雜,需要處理事件的就緒狀態,因此在實際應用中通常會使用NIO框架或者基于NIO的高級框架,如Netty。
AIO
在Java中,AIO(Asynchronous I/O)是一種基于事件和回調機制的I/O模型,相比于傳統的BIO(Blocking I/O)和NIO(Non-blocking I/O),AIO更加適用于處理大量并發連接。下面我將詳細介紹AIO的實現原理。
-
異步I/O:
AIO的核心是異步I/O,它允許一個線程在等待數據就緒的同時繼續做其他事情,當數據就緒后通過回調機制來處理數據。這種模型相比于NIO更加靈活,因為不需要手動檢查就緒狀態,而是通過事件通知來處理。 -
核心組件:
- 異步通道(AsynchronousChannel):用于進行異步I/O操作,包括文件和套接字等。
- 異步操作結果(AsynchronousResult):用于存儲異步操作的結果,可以通過回調方式獲取結果。
- 異步處理器(AsynchronousHandler):用于處理異步操作完成后的回調。
-
實現原理:
- 服務端:服務端通過AsynchronousServerSocketChannel監聽連接請求,一旦有連接到來,會調用accept方法,并通過回調方式處理連接就緒事件。
- 客戶端:客戶端通過AsynchronousSocketChannel向服務端發起連接請求,連接建立后也可以通過回調方式處理后續的讀寫操作。
-
簡單的AIO服務器示例代碼:
實現思路:針對企業級生產環境中高可用的通信需求,以下是一個更完善的AIO服務端和客戶端的Java代碼。該代碼考慮了各種可能遇到的問題,并給出了切實可行的異常解決方案。同時,引入了日志打印服務,使用了Java自帶的Logger類來記錄日志,并使用了線程池來處理客戶端的連接請求和數據讀寫操作,以提高并發處理能力。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; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Logger;public class AIOServer {private static final Logger logger = Logger.getLogger(AIOServer.class.getName());private static final ExecutorService executor = Executors.newFixedThreadPool(10);public static void main(String[] args) {try {AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();serverSocketChannel.bind(new InetSocketAddress(8080));serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {@Overridepublic void completed(AsynchronousSocketChannel clientChannel, Void attachment) {serverSocketChannel.accept(null, this); // 接受下一個連接executor.execute(() -> handleRead(clientChannel));}@Overridepublic void failed(Throwable exc, Void attachment) {logger.severe("Error in accepting connection: " + exc.getMessage());}});// 阻止主線程退出Thread.currentThread().join();} catch (IOException | InterruptedException e) {logger.severe("Error in AIO server: " + e.getMessage());}}private static void handleRead(AsynchronousSocketChannel clientChannel) {ByteBuffer buffer = ByteBuffer.allocate(1024);clientChannel.read(buffer, null, new CompletionHandler<Integer, Void>() {@Overridepublic void completed(Integer bytesRead, Void attachment) {if (bytesRead == -1) {try {clientChannel.close();} catch (IOException e) {logger.severe("Error in closing client channel: " + e.getMessage());}return;}buffer.flip();byte[] data = new byte[bytesRead];buffer.get(data);logger.info("Received from client: " + new String(data));// 可以在這里處理接收到的數據buffer.clear();clientChannel.read(buffer, null, this); // 繼續讀取數據}@Overridepublic void failed(Throwable exc, Void attachment) {logger.severe("Error in reading from client: " + exc.getMessage());}});} }
-
簡單的AIO客戶端示例代碼:
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger;public class AIOClient {private static final Logger logger = Logger.getLogger(AIOClient.class.getName());private static final ExecutorService executor = Executors.newFixedThreadPool(10);public static void main(String[] args) {try {AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();socketChannel.connect(new InetSocketAddress("localhost", 8080), null, new CompletionHandler<Void, Void>() {@Overridepublic void completed(Void result, Void attachment) {String message = "Hello, server!";ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());socketChannel.write(buffer, null, new CompletionHandler<Integer, Void>() {@Overridepublic void completed(Integer bytesWritten, Void attachment) {if (buffer.hasRemaining()) {socketChannel.write(buffer, null, this); // 繼續寫入數據} else {buffer.clear();socketChannel.read(buffer, null, new CompletionHandler<Integer, Void>() {@Overridepublic void completed(Integer bytesRead, Void attachment) {buffer.flip();byte[] data = new byte[bytesRead];buffer.get(data);logger.info("Received from server: " + new String(data));// 可以在這里處理接收到的數據}@Overridepublic void failed(Throwable exc, Void attachment) {logger.severe("Error in reading from server: " + exc.getMessage());}});}}@Overridepublic void failed(Throwable exc, Void attachment) {logger.severe("Error in writing to server: " + exc.getMessage());}});}@Overridepublic void failed(Throwable exc, Void attachment) {logger.severe("Error in connecting to server: " + exc.getMessage());}});// 阻止主線程退出Thread.currentThread().join();} catch (IOException | InterruptedException e) {logger.severe("Error in AIO client: " + e.getMessage());}} }
-
適用場景:
AIO適用于需要處理大量并發連接且對性能要求較高的場景,例如高性能的網絡服務器、金融交易系統等。
總的來說,AIO通過異步I/O和事件回調機制,實現了高效的并發處理能力,相比于NIO更加靈活和高效。然而,AIO在Java中的實現相對較新,需要較高的技術要求,因此在實際應用中通常會使用成熟的AIO框架或者基于AIO的高級框架。
在Java中,有一些成熟的AIO框架或者基于AIO的高級框架,它們提供了更加便捷和高效的異步I/O編程方式。以下是一些常用的框架:
-
Netty:
Netty是一個基于NIO的高性能網絡通信框架,但它也提供了對AIO的支持。Netty的異步事件驅動模型和高度可定制的架構使得它成為構建高性能、可擴展的網絡應用程序的理想選擇。Netty提供了豐富的功能,包括TCP/UDP傳輸、HTTP編解碼、WebSocket支持等,廣泛應用于網絡服務器、分布式系統等領域。 -
Grizzly:
Grizzly是一個基于NIO的高性能網絡框架,它提供了對AIO的支持,并且具有高度可擴展性和靈活性。Grizzly可以用于構建高性能的Web服務器、應用服務器等網絡應用。 -
Apache MINA:
Apache MINA是一個基于NIO的網絡應用框架,它提供了對AIO的支持,并且具有良好的擴展性和靈活性。MINA可以用于構建各種類型的網絡應用,包括游戲服務器、即時通訊服務器等。
這些框架都提供了對AIO的封裝和抽象,簡化了異步I/O編程的復雜性,同時提供了豐富的功能和高性能的網絡通信能力。在實際應用中,選擇合適的框架取決于具體的需求和項目背景,但無論選擇哪個框架,都可以極大地簡化異步I/O編程的復雜性,提高開發效率和系統性能。