• Protocol Buffers教程


    今天想比较下pb和fastjson两个序列化后的大小。再看了一下pb序列化

    pb官网:https://developers.google.com/protocol-buffers/

    pb是啥

    1 What are protocol buffers?
    2 Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, 
    and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured
    data to and from a variety of data streams and using a variety of languages.

    一个序列化框架,比xml序列化后的空间更小,更快,更简单。定义好实体文件,可以生成指定语言代码,如java, c++等,这也是一个很重要的功能吧

    官网demo教程:

    1. 定义实体文件

    addressbook.proto

    syntax = "proto2";
    
    package demo;
    
    option java_package = "com.gxf.demo";
    option java_outer_classname = "AddressBookProtos";
    
    message Person {
      required string name = 1;
      required int32 id = 2;
      optional string email = 3;
    
      enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
      }
    
      message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];
      }
    
      repeated PhoneNumber phones = 4;
    }
    
    message AddressBook {
      repeated Person people = 1;
    }

    3. 下载、安装pb编译器

    https://github.com/google/protobuf/releases/

    解压, configure,  make, make install

    4. 编译实体文件

    protoc -I=. --java_out=. ./addressbook.proto

    5. java demo

    package com.gxf.demo;
    
    public class PtotobufDemo {
    
        public static void main(String[] args) {
            AddressBookProtos.Person gxf =
                    AddressBookProtos.Person.newBuilder()
                            .setId(1234)
                            .setName("guan xianseng")
                            .setEmail("guanxianseng@example.com")
                            .addPhones(
                                    AddressBookProtos.Person.PhoneNumber.newBuilder()
                                            .setNumber("555-4321")
                                            .setType(AddressBookProtos.Person.PhoneType.HOME))
                            .build();
    
            System.out.println(gxf);
    
            byte[] bytes = gxf.toByteArray();
            System.out.println(bytes.length);
        }
    }

    用fastjson序列化pb生成的实体报错了,要比较还要定义实体类,枚举等,就不折腾了

  • 相关阅读:
    jquery键盘事件
    如何将奇艺、优酷等平台的视频嵌入到项目中
    ubuntu 10.04 常用 设置
    博客风格收集
    多张图片上传预览
    动态计算输入框字符个数
    Ubuntu Linux下设置IP的配置命令
    js事件浏览器兼容
    开源软件下载站
    PHPstrom的一个小技巧
  • 原文地址:https://www.cnblogs.com/luckygxf/p/9193457.html
Copyright © 2020-2023  润新知