java中Protobuf的使用執行個體

來源:互聯網
上載者:User

 最近公司項目中有埋點的需求,採用的是protocolbuffer的資料格式,所以去研究了protobuf的使用,在此記錄一下

1.什麼是protocolbuffer?

protocol buffer是google的一個開源項目,它是用於結構化資料序列化的靈活、高效、自動的方法,例如XML,不過它比xml更小、更快、也更簡單。你可以定義自己的資料結構,然後使用代碼產生器產生的程式碼來讀寫這個資料結構。你甚至可以在無需重新部署程式的情況下更新資料結構。

2.使用

2.1下載protoc-2.4.1-win32.zip,http://download.csdn.net/detail/tiandiwuya/9792888

2.2下載 一個protobuf-Java-2.4.1.jar檔案,http://download.csdn.net/detail/tiandiwuya/9792889

2.3.用記事本編寫一個.proto檔案:

如:我編寫的是msg.proto

package protobuf;
option java_package = "com.sq.protobuf";
option java_outer_classname = "FirstProtobuf";
message testBuf  {
  required int32 ID = 1;
  required string Url = 2;
} 將其放在與剛解壓的protoc.exe同級目錄中。
2.4使用如下命令編譯這個檔案:

protoc.exe --java_out./ msg.proto


2.5將產生的FirstProtobuf.java檔案引入eclipse,把下載的protobuf-java-2.4.1.jar也引入工程

2.6建立測試檔案

public class test2 {public static void main(String[] args) {//序列化FirstProtobuf.testBuf.Builder builder = FirstProtobuf.testBuf.newBuilder();builder.setID(117);builder.setUrl("bangde");// testBufFirstProtobuf.testBuf info = builder.build();byte[] result = info.toByteArray();System.out.println("還原序列化過程:"+result.toString());//還原序列化過程try {FirstProtobuf.testBuf testBuf = FirstProtobuf.testBuf.parseFrom(result);System.out.println("還原序列化過程:"+"\n"+testBuf);} catch (InvalidProtocolBufferException e) {e.printStackTrace();}}}
結果:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.