美文网首页
protobuf使用方法

protobuf使用方法

作者: 我看Android | 来源:发表于2019-07-26 16:41 被阅读0次

上半年公司开了新项目,更改了网络通信中数据结构,由json转化为了protobuf ,蓦然发现挺好用

近期项目即将结束,写篇文章记录一下protobuf使用方法。

配置

在项目的根gradle配置如下

dependencies {
     classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.6'
}

在gradle中配置如下:

apply plugin: 'com.google.protobuf'

android {

    sourceSets {

        main {

            // 定义proto文件目录

            proto {

                srcDir 'src/main/proto'

                include '**/*.proto'

            }

        }

    }

}



dependencies {

    // 定义protobuf依赖,使用精简版

       api'com.google.protobuf:protobuf-lite:3.0.0'

       api('com.squareup.retrofit2:converter-protobuf:2.2.0') {

           excludegroup:'com.google.protobuf',module:'protobuf-java'

      }

}

protobuf {

    protoc {

        artifact = 'com.google.protobuf:protoc:3.0.0'

    }

    plugins {

        javalite {

            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'

        }

    }

    generateProtoTasks {

        all().each { task ->

            task.plugins {

                javalite {}

            }

        }

    }

}

定义数据结构

syntax="proto3";//声明版本

option java_package="com.*.*.*.protobuf"; //生成文件所在目录

message Event{

int32 id = 1;

int32 code = 2;

uint64 timestamp = 3;

string jsonBody = 4;

PbBody pbBody = 5;

string jsonHeader = 6;

string selfBody = 7;

}

message PbBody{

bytes voice = 1;

}

项目中将数据格式统一定义 因此只需定义数据基类,其余进行数据填充即可

对比json xml

XML、JSON、ProtoBuf 都具有数据结构化和数据序列化的能力
XML、JSON 注重数据结构化,在代码可读性及语义表达能力较PB更优。
ProtoBuf 在数据序列化的效率、占用空间上更优但代码可读性差,语义表达能力不足
ProtoBuf 的应用场景更为明确,XML、JSON 的应用场景更为丰富。

相关文章

网友评论

      本文标题:protobuf使用方法

      本文链接:https://www.haomeiwen.com/subject/btldrctx.html