我們有一個使用UDP多播發送日誌事件的日誌記錄系統。事件發生率約爲10,000次/秒,平均事件大小約爲2Kb。Java NIO UDP多播 - 丟棄的數據包
在每次測試期間,應用程序的NIO版本都會失去一小部分事件(大約12M的約2000個事件)。有沒有人有這方面的見解?
示例代碼: 沒有NIO:
byte[] buf = new byte[65535];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
while (!Thread.currentThread().isInterrupted()) {
socket.receive(packet);
final byte[] tmpBuffer = new byte[packet.getLength()];
System.arraycopy(packet.getData(), 0, tmpBuffer, 0,
tmpBuffer.length);
insertToNonBlockingQueue(tmpBuffer, packet.getSocketAddress());
}
} catch (Throwable t) {
throw new RuntimeException("Encountered exception in Acceptor", t);
} finally {
Util.closeQuietly(socket);
}
隨着NIO:
ByteBuffer inBuffer = ByteBuffer.allocate(65535);
try {
while (!Thread.currentThread().isInterrupted()) {
SocketAddress addr = channel.receive(inBuffer);
inBuffer.flip();
final byte[] tmpBuffer = new byte[inBuffer.limit()];
inBuffer.get(tmpBuffer);
inBuffer.clear();
insertToNonBlockingQueue(tmpBuffer, addr);
}
} catch (ClosedByInterruptException ex) {
log.info("Channel closed by interrupt"); // normal shutdown
} catch (Throwable t) {
throw new RuntimeException("Encountered exception in Acceptor", t);
} finally {
Util.closeQuietly(channel);
}
這兩個監聽器在同一時間,每一個非NIO版本捕獲所有,而日誌事件時運行NIO版本錯過了一些。這不是網絡問題,因爲即使我們將代碼切換到計算機上的其他版本,也是如此。
對不起,我錯過了包括清除當我複製粘貼代碼時,我有代碼中的buffer.clear(),我編輯了張貼以反映它 – user2677485