![](/img/trans.png)
[英]How to convert protocol buffers binary to JSON using the descriptor in Java
[英]Using protocol buffers for binary logging
我們正在考慮使用Protocol Buffers進行二進制日志記錄,因為:
也就是說,我們應該如何處理它並不明顯,因為API傾向於專注於創建整個對象,因此將DataLogEntry列表包裝為DataLogFile中的重復字段將是您在消息傳遞方面所做的事情,但是我們真正想要的只是能夠編寫然后讀取整個DataLogEntry,將其附加到文件的末尾。
我們這樣做的第一個問題是這樣做(在測試中:
FileInputStream fileIn = new FileInputStream(logFile);
CodedInputStream in = CodedInputStream.newInstance(fileIn);
while(!in.isAtEnd()) {
DataLogEntry entry = DataLogEntry.parseFrom(in);
// ... do stuff
}
僅導致從流中讀取1個DataLogEntry。 沒有isAtEnd,它永遠不會停止。
思考?
編輯:我已經切換到使用entry.writeDelimitedTo和BidLogEntry.parseDelimitedFrom,這似乎工作...
根據我對協議緩沖區的理解,它不支持單個流中的多個消息。 因此,您可能需要自己跟蹤消息的邊界。 您可以通過在日志中的每條消息之前存儲消息的大小來完成此操作。
public class DataLog {
public void write(final DataOutputStream out, final DataLogEntry entry) throws IOException {
out.writeInt(entry.getSerializedSize());
CodedOutputStream codedOut = CodedOutputStream.newInstance(out);
entry.writeTo(codedOut);
codedOut.flush();
}
public void read(final DataInputStream in) throws IOException {
byte[] buffer = new byte[4096];
while (true) {
try {
int size = in.readInt();
CodedInputStream codedIn;
if (size <= buffer.length) {
in.read(buffer, 0, size);
codedIn = CodedInputStream.newInstance(buffer, 0, size);
} else {
byte[] tmp = new byte[size];
in.read(tmp);
codedIn = CodedInputStream.newInstance(tmp);
}
DataLogEntry.parseFrom(codedIn);
// ... do stuff
}
catch (final EOFException e) {
break;
}
}
}
}
注意:我已經使用EOFException來查找文件的結尾,您可能希望使用分隔符或跟蹤手動讀取的字節數。
至少2.4.0a,這很容易。 用writeDelimitedTo寫你的消息。 無需直接使用編碼流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.