Protobuffer 和 Json 深度對比

CharliChen發表於2017-01-24

JSON相信大家都知道是什麼東西,如果不知道,那可就真的OUT了,GOOGLE一下去。這裡就不介紹啥的了。

Protobuffer大家估計就很少聽說了,但如果說到是GOOGLE搞的,相信大家都會有興趣去試一下,畢竟GOOGLE出口,多屬精品。

Protobuffer是一個類似JSON的一個傳輸協議,其實也不能說是協議,只是一個資料傳輸的東西罷了。

那它跟JSON有什麼區別呢?

跨語言,這是它的一個優點。它自帶了一個編譯器,protoc,只需要用它進行編譯,可以編譯成JAVApythonC++程式碼,暫時只有這三個,其他就暫時不要想了,然後就可以直接使用,不需要再寫任何其他程式碼。連解析的那些都已經自帶有的。JSON當然也是跨語言的,但這個跨語言是建立在編寫程式碼的基礎上。

如果想再深入瞭解的,可以去看看:

https://developers.google.com/protocol-buffers/docs/overview

好了,廢話不多說,我們直接來看看,為什麼我們需要對比protobuffer(下面簡稱GPB)和JSON

1、JSON因為有一定的格式,並且是以字元存在的,在資料量上還有可以壓縮的空間。而GPB上大資料量時,空間比JSON小很多,等一下的例子我們可以看到。

2、JSON各個庫之間的效率相差比較大,jackson庫和GSON就大概有5-10的差距(這個只做過一次測試,如有誤,請大家輕拍)。而GPB只需要一個,沒有所謂的多個庫的區別。當然這個點只是弄出來湊數的,可以忽略不計哈。

 

Talk is cheap,Just show me the code。

在程式界,程式碼永遠是王道,下面就直接來程式碼吧。

上程式碼前,大家要先下載protobuffer,在這裡:

https://code.google.com/p/protobuf/downloads/list

注意,需要下載兩個,一個是complier,另外一個是source code,相信這個難不倒大家了,這裡略過。

1、首先,GPB是需要有一個類似類定義的檔案,叫proto檔案 。

我們以學生和老師的例子來進行一個例子:

我們有以下兩個檔案:student.proto

 

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">option java_package = "com.shun";  
  2. option java_outer_classname = "StudentProto";  
  3.   
  4. message Student {  
  5.     required int32 id = 1;  
  6.     optional string name = 2;  
  7.     optional int32 age = 3;  
  8. }</span>  

 teacher.proto

 

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">import "student.proto";  
  2. option java_package = "com.shun";  
  3. option java_outer_classname = "TeacherProto";  
  4.   
  5. message Teacher {  
  6.     required int32 id = 1;  
  7.     optional string name = 2;  
  8.   
  9.     repeated Student student_list = 3;  
  10. }</span>  

這裡我們遇到了一些比較奇怪的東西:

import,int32,repated,required,optional,option等

一個個來吧:

1)import表示引入其他的proto檔案

2)required,optional表示欄位是否可選,這個決定了該欄位有無值的情況下protobuffer會進行什麼處理。如果標誌了required,但當處理時,該欄位沒有進行傳值,則會報錯;如果標誌了optional,不傳值則不會有什麼問題。

3)repeated相信應該都看得懂了,就是是否重複,跟JAVA裡面的list類似

4)message就是相當於class

5)option表示選項,其中的java_package表示包名,即生成JAVA程式碼時使用的包名,java_outer_classname即為類名,注意這個類名不能跟下面的message中的類名相同。

至於還有其他的選項和相關型別的,請參觀官方文件。

 

2、有了這幾個檔案,我們能怎麼樣呢?

記得上面下載的編譯器了吧,解壓出來,我們得到一個protoc.exe,這當然是windows下的,我沒弄其他系統的,有興趣的同學去折騰下羅。

加到path(加不加可以隨便,只是方不方便而已),然後就可以通過上面的檔案生成我們需要的類檔案了。

protoc --java_out=存放原始碼的路徑 --proto_path=proto檔案的路徑 proto具體檔案

--proto_path指定的是proto檔案的資料夾路徑,並不是單個檔案,主要是為了import檔案查詢使用的,可以省略

 

如我需要把原始碼放在D:\protobufferVsJson\src,而我的proto檔案存放在D:\protoFiles

那麼我的編譯命令就是:

protoc --java_out=D:\protobufferVsJson\src 

D:\protoFiles\teacher.proto D:\protoFiles\student.proto

注意,這裡最後的檔案,我們需要指定需要編譯的所有檔案

 

編譯後可以看到生成的檔案。

程式碼就不貼出來了,太多了。大家可以私下看看,程式碼裡面有一大堆Builder,相信一看就知道是建造者模式了。

這時可以把程式碼貼到你的專案中了,當然,錯誤一堆了。

 

記得我們前面下載的原始碼嗎?解壓它吧,不要手軟。然後找到src/main/java/複製其中的一堆到你的專案,當然,你也可以ant或者maven編譯,但這兩個東西我都不熟,就不獻醜了,我還是習慣直接複製到專案中。


程式碼出錯,哈哈,正常。不知道為何,GOOGLE非要留下這麼個坑給我們。

翻回到protobuffer目錄下的\java看到有個readme.txt了吧,找到一句:

看來看去,感覺這個程式碼會有點奇怪的,好像錯錯的感覺,反正我是沒按那個執行,我的命令是:

 

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">protoc --java_out=還是上面的放程式碼的地方 proto檔案的路徑(這裡是descriptor.proto檔案的路徑)</span>  

執行後,我們可以看到程式碼中的錯誤木有了。

 

3、接下來當然就是測試了。

我們先進行GPB寫入測試:

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">package com.shun.test;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import com.shun.StudentProto.Student;  
  9. import com.shun.TeacherProto.Teacher;  
  10.   
  11. public class ProtoWriteTest {  
  12.   
  13.     public static void main(String[] args) throws IOException {  
  14.           
  15.         Student.Builder stuBuilder = Student.newBuilder();  
  16.         stuBuilder.setAge(25);  
  17.         stuBuilder.setId(11);  
  18.         stuBuilder.setName("shun");  
  19.           
  20.         //構造List  
  21.         List<Student> stuBuilderList = new ArrayList<Student>();  
  22.         stuBuilderList.add(stuBuilder.build());  
  23.           
  24.         Teacher.Builder teaBuilder = Teacher.newBuilder();  
  25.         teaBuilder.setId(1);  
  26.         teaBuilder.setName("testTea");  
  27.         teaBuilder.addAllStudentList(stuBuilderList);  
  28.           
  29.         //把gpb寫入到檔案  
  30.         FileOutputStream fos = new FileOutputStream("C:\\Users\\shun\\Desktop\\test\\test.protoout");  
  31.         teaBuilder.build().writeTo(fos);  
  32.         fos.close();  
  33.     }  
  34.   
  35. }</span>  

我們去看看檔案,如無意外,應該是生成了的。

生成了之後,我們肯定要讀回它的。

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">package com.shun.test;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6.   
  7. import com.shun.StudentProto.Student;  
  8. import com.shun.TeacherProto.Teacher;  
  9.   
  10. public class ProtoReadTest {  
  11.   
  12.     public static void main(String[] args) throws FileNotFoundException, IOException {  
  13.           
  14.         Teacher teacher = Teacher.parseFrom(new FileInputStream("C:\\Users\\shun\\Desktop\\test\\test.protoout"));  
  15.         System.out.println("Teacher ID:" + teacher.getId() + ",Name:" + teacher.getName());  
  16.         for (Student stu:teacher.getStudentListList()) {  
  17.             System.out.println("Student ID:" + stu.getId() + ",Name:" + stu.getName() + ",Age:" + stu.getAge());  
  18.         }  
  19.     }  
  20.   
  21. }</span>  

程式碼很簡單,因為GPB生成的程式碼都幫我們完成了。

上面知道基本的用法了,我們重點來關注GPBJSON生成檔案大小的區別,JSON的詳細程式碼我這裡就不貼了,之後會貼出示例,大家有興趣可以下載。

這裡我們用Gson來解析JSON,下面只給出物件轉換成JSON後寫出檔案的程式碼:

兩個類StudentTeacher的基本定義就不弄了,大家隨意就行,程式碼如下:

 

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">package com.shun.test;  
  2.   
  3. import java.io.FileWriter;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import com.google.gson.Gson;  
  9. import com.shun.Student;  
  10. import com.shun.Teacher;  
  11.   
  12. public class GsonWriteTest {  
  13.   
  14.     public static void main(String[] args) throws IOException {  
  15.         Student stu = new Student();  
  16.         stu.setAge(25);  
  17.         stu.setId(22);  
  18.         stu.setName("shun");  
  19.           
  20.         List<Student> stuList = new ArrayList<Student>();  
  21.         stuList.add(stu);  
  22.           
  23.         Teacher teacher = new Teacher();  
  24.         teacher.setId(22);  
  25.         teacher.setName("shun");  
  26.         teacher.setStuList(stuList);  
  27.           
  28.         String result = new Gson().toJson(teacher);  
  29.         FileWriter fw = new FileWriter("C:\\Users\\shun\\Desktop\\test\\json");  
  30.         fw.write(result);  
  31.         fw.close();  
  32.     }  
  33.   
  34. }</span>  

接下來正式進入我們的真正測試程式碼了,前面我們只是在列表中放入一個物件,接下來,我們依次測試100,1000,10000,100000,1000000,5000000這幾個數量的GPBJSON生成的檔案大小。

改進一下之前的GPB程式碼,讓它生成不同數量的列表,再生成檔案:

 

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">package com.shun.test;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import com.shun.StudentProto.Student;  
  9. import com.shun.TeacherProto.Teacher;  
  10.   
  11. public class ProtoWriteTest {  
  12.   
  13.     public static final int SIZE = 100;  
  14.       
  15.     public static void main(String[] args) throws IOException {  
  16.           
  17.         //構造List  
  18.         List<Student> stuBuilderList = new ArrayList<Student>();  
  19.         for (int i = 0; i < SIZE; i ++) {  
  20.             Student.Builder stuBuilder = Student.newBuilder();  
  21.             stuBuilder.setAge(25);  
  22.             stuBuilder.setId(11);  
  23.             stuBuilder.setName("shun");  
  24.               
  25.             stuBuilderList.add(stuBuilder.build());  
  26.         }  
  27.           
  28.         Teacher.Builder teaBuilder = Teacher.newBuilder();  
  29.         teaBuilder.setId(1);  
  30.         teaBuilder.setName("testTea");  
  31.         teaBuilder.addAllStudentList(stuBuilderList);  
  32.           
  33.         //把gpb寫入到檔案  
  34.         FileOutputStream fos = new FileOutputStream("C:\\Users\\shun\\Desktop\\test\\proto-" + SIZE);  
  35.         teaBuilder.build().writeTo(fos);  
  36.         fos.close();  
  37.     }  
  38.   
  39. }</span>  

 這裡的SIZE依次改成我們上面據說的測試數,可以得到如下:

 


 
然後我們再看看JSON的測試程式碼:

 

 

Java程式碼  收藏程式碼
  1. <span style="font-size: 16px;">package com.shun.test;  
  2.   
  3. import java.io.FileWriter;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import com.google.gson.Gson;  
  9. import com.shun.Student;  
  10. import com.shun.Teacher;  
  11.   
  12. public class GsonWriteTest {  
  13.   
  14.     public static final int SIZE = 100;  
  15.       
  16.     public static void main(String[] args) throws IOException {  
  17.           
  18.         List<Student> stuList = new ArrayList<Student>();  
  19.         for (int i = 0; i < SIZE; i ++) {  
  20.             Student stu = new Student();  
  21.             stu.setAge(25);  
  22.             stu.setId(22);  
  23.             stu.setName("shun");  
  24.               
  25.             stuList.add(stu);  
  26.         }  
  27.           
  28.           
  29.         Teacher teacher = new Teacher();  
  30.         teacher.setId(22);  
  31.         teacher.setName("shun");  
  32.         teacher.setStuList(stuList);  
  33.           
  34.         String result = new Gson().toJson(teacher);  
  35.         FileWriter fw = new FileWriter("C:\\Users\\shun\\Desktop\\test\\json" + SIZE);  
  36.         fw.write(result);  
  37.         fw.close();  
  38.     }  
  39.   
  40. }</span>  

 同樣的方法修改SIZE,並作相應的測試。

可以明顯得看到json的檔案大小跟GPB的檔案大小在資料量慢慢大上去的時候就會有比較大的差別了,JSON明顯要大上許多。


上面的表應該可以看得比較清楚了,在大資料的GPB是非常佔優勢的,但一般情況下客戶端和服務端並不會直接進行這麼大資料的互動,大資料主要發生在伺服器端的傳輸上,如果你面對需求是每天需要把幾百M的日誌檔案傳到另外一臺伺服器,那麼這裡GPB可能就能幫你的大忙了。

 

 

說是深度對比,其實主要對比的是大小方面,時間方面可比性不會太大,也沒相差太大。

文章中選擇的Gson解析器,有興趣的朋友可以選擇Jackson或者fastjson,又或者其他的,但生成的檔案大小是一樣的,只是解析時間有區別。

相關文章