Protobuffer和json深度对比

发表于2015-12-20
评论1 2.3k浏览

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

 

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

 teacher.proto

 

1
2
3
4
5
6
7
8
9
10
<span style="font-size: 16px;">import "student.proto";
option java_package = "com.shun";
option java_outer_classname = "TeacherProto";
 
message Teacher {
    required int32 id = 1;
    optional string name = 2;
 
    repeated Student student_list = 3;
}</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:protobufferVsJsonsrc,而我的proto文件存放在D:protoFiles

那么我的编译命令就是:

protoc --java_out=D:protobufferVsJsonsrc 

D:protoFilesteacher.proto D:protoFilesstudent.proto

注意,这里最后的文件,我们需要指定需要编译的所有文件

 

编译后可以看到生成的文件。

代码就不贴出来了,太多了。大家可以私下看看,代码里面有一大堆Builder,相信一看就知道是建造者模式了。

这时可以把代码贴到你的项目中了,当然,错误一堆了。

 

记得我们前面下载的源代码吗?解压它吧,不要手软。然后找到src/main/java/复制其中的一堆到你的项目,当然,你也可以ant或者maven编译,但这两个东西我都不熟,就不献丑了,我还是习惯直接复制到项目中。


代码出错,哈哈,正常。不知道为何,GOOGLE非要留下这么个坑给我们。

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

看来看去,感觉这个代码会有点奇怪的,好像错错的感觉,反正我是没按那个执行,我的命令是:

 

1
<span style="font-size: 16px;">protoc --java_out=还是上面的放代码的地方 proto文件的路径(这里是descriptor.proto文件的路径)</span>

执行后,我们可以看到代码中的错误木有了。

 

3接下来当然就是测试了。

我们先进行GPB写入测试:

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

我们去看看文件,如无意外,应该是生成了的。

生成了之后,我们肯定要读回它的。

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

代码很简单,因为GPB生成的代码都帮我们完成了。

上面知道基本的用法了,我们重点来关注GPBJSON生成文件大小的区别,JSON的详细代码我这里就不贴了,之后会贴出示例,大家有兴趣可以下载。

这里我们用Gson来解析JSON,下面只给出对象转换成JSON后写出文件的代码:

两个类StudentTeacher的基本定义就不弄了,大家随意就行,代码如下:

 

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

接下来正式进入我们的真正测试代码了,前面我们只是在列表中放入一个对象,接下来,我们依次测试100,1000,10000,100000,1000000,5000000这几个数量的GPBJSON生成的文件大小。

改进一下之前的GPB代码,让它生成不同数量的列表,再生成文件:

 

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

 这里的SIZE依次改成我们上面据说的测试数,可以得到如下:

 


 
然后我们再看看JSON的测试代码:

 

 

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

 同样的方法修改SIZE,并作相应的测试。

可以明显得看到json的文件大小跟GPB的文件大小在数据量慢慢大上去的时候就会有比较大的差别了,JSON明显要大上许多。


上面的表应该可以看得比较清楚了,在大数据的GPB是非常占优势的,但一般情况下客户端和服务端并不会直接进行这么大数据的交互,大数据主要发生在服务器端的传输上,如果你面对需求是每天需要把几百M的日志文件传到另外一台服务器,那么这里GPB可能就能帮你的大忙了。

 

说是深度对比,其实主要对比的是大小方面,时间方面可比性不会太大,也没相差太大。

文章中选择的Gson解析器,有兴趣的朋友可以选择Jackson或者fastjson,又或者其他的,但生成的文件大小是一样的,只是解析时间有区别。


如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

0个评论