Java序列化神器——Jprotobuf(小白篇)

proto开发神器——Jprotobuf(小白篇)
前言:
最近对一个项目做升级,内部有大对象需要存储到缓存上去,考虑到存储资源和性能问题,我们决定对生成的对象进行压缩,首先想到的是gzip压
缩,但是架构开始的时候,同事张某提议使用Google 的proto,发了几个文档看了一下,上手有点懵,这玩意的使用比对象转json压缩可复杂太多了,让人
有点恶心:于是乎,同事张某又发了一个插件(百度开发的),据说这个插件比原来使用简单的多,这是接入文档: https://segmentfault.com/a
/1190000039200121 ,但是,我看了一会,我认为这个接入文档写的一点也不简单,写得挺全乎但是文章结构散乱,而且很多没必要出现的东西会误导新人的
使用,因此我认为这个更适合已经成功接入并使用的人进一步考究,下面我整理一个小白入门文档,看完这篇,小时牛刀后你就能继续看上边提到的说明文
档,最后你可以去看官方文档;
proto的有点和说明我这里不再赘述,网上一堆

一、官方使用方法(没有插件前)

1、你需要去官网下载: protoc.exe 
2、你需要 定义.proto说明文件,举个栗子:你需要对一个名叫Student的类的对象进行序列化压缩,那么你就要写一个文件:Student.proto,至于这个文件
内容,参考上面那个链接
3、使用protoc.exe 编译.proto文件
4、编译生成的Java文件,利用protobuf API进行序列化与反序化操作
对了,你还要再项目里面引入相关依赖,这个我忘记说了......
怎末,是不是很恶心,要不是项目需要,鬼愿意使用这玩意

二、使用这个插件(入门版)

1、引入依赖(SLF4J相关依赖请自行引入)


 com.baidu
 jprotobuf
 2.4.5


 com.baidu
 jprotobuf-precompile-plugin
 2.2.2
2、写两个类(写一个也行),我这里写了Student和Teacher两个类
@Data
@ProtobufClass
public class StudentPo extends PersonPo{
 @Protobuf(fieldType= FieldType.STRING, order=1)
 private String schoolName;
 @Protobuf(fieldType= FieldType.INT32, order=2)
 private Integer grade;
 @Protobuf(fieldType= FieldType.OBJECT, order=3)
 private List teacherPos;
}
@Data
@ProtobufClass
public class TeacherPo{
 private String name;
 private Integer age;
 private Integer sex;
}
3、直接写一个main方法 。。。操作
public static void main(String[] args) {
 System.out.println("main");
 StudentPo student = createStudentEntity();
 try {
     // 
     String jsonT = JSON.toJSONString(student);
     byte[] bytes = jsonT.getBytes();
     System.out.println(""+bytes.length);
     //
     //Protobuf
     // 
     Codec studentPoCodec = ProtobufProxy.create(StudentPo.class);
     byte[] bb = studentPoCodec.encode(student);
     System.out.println(""+bb.length);
     // 
     StudentPo newStudent = studentPoCodec.decode(bb);
     System.out.println(""+JSON.toJSONString(newStudent));
 } catch (Exception e) {
     e.printStackTrace();
}

//
public static StudentPo createStudentEntity(){
 StudentPo student = new StudentPo();
 student.setName("");
 student.setGrade(5);
 student.setAge(20);
 student.setSex(1);
 student.setSchoolName("");
 TeacherPo teacher = new TeacherPo();
 teacher.setAge(28);
 teacher.setSex(0);
 teacher.setName("");
 List teacherPos = new ArrayList();
 teacherPos.add(teacher);
 student.setTeacherPos(teacherPos);
 return student;
}

你可能感兴趣的:(springboot,Java,java,序列化)