当前位置 博文首页 > Python使用protobuf序列化和反序列化的实现

    Python使用protobuf序列化和反序列化的实现

    作者:叫我阿柒啊 时间:2021-06-01 18:05

    protobuf介绍

    protobuf是一种二进制的序列化格式,相对于json来说体积更小,传输更快。

    安装protobuf

    安装protobuf的目的主要用来将proto文件编译成python、c、Java可调用的接口。

    # 如果gcc版本较低,需要升级gcc
    wget https://main.qcloudimg.com/raw/d7810aaf8b3073fbbc9d4049c21532aa/protobuf-2.6.1.tar.gz
    tar -zxvf protobuf-2.6.1.tar.gz -C /usr/local/ && cd /usr/local/protobuf-2.6.1
    ./configure 
    make && make install
    # 可以在/etc/profile或者~/.bash_profile末尾设置永久有效
    export PATH=$PATH:/usr/local/protobuf-2.6.1/bin
    

    使用下面命令查看是否安装成功。

    [root@CodeOnTheRoad ~]# protoc --version
    libprotoc 2.6.1

    构建python接口

    创建cls.proto文件,定义序列化结构:

    package cls;
    
    message Log
    {
        message Content
        {
            required string key   = 1; // 每组字段的 key
            required string value = 2; // 每组字段的 value
        }
        required int64   time     = 1; // 时间戳,UNIX时间格式
        repeated Content contents = 2; // 一条日志里的多个kv组合
    }
    
    message LogTag
    {
        required string key       = 1;
        required string value     = 2;
    }
    
    message LogGroup
    {
        repeated Log    logs        = 1; // 多条日志合成的日志数组
        optional string contextFlow = 2; // 目前暂无效用
        optional string filename    = 3; // 日志文件名
        optional string source      = 4; // 日志来源,一般使用机器IP
        repeated LogTag logTags     = 5;
    }
    
    message LogGroupList
    {
        repeated LogGroup logGroupList = 1; // 日志组列表
    }
     
    
    

    只用下面命令将proto文件转换为python可调用的接口。

    protoc cls.proto --python_out=./ 
    

    执行完后,在此目录下生成cls_pb2.py。

    序列化

    import cls_pb2 as cls
    import time
    
    # 构建protoBuf日志内容
    LogLogGroupList = cls.LogGroupList()
    
    LogGroup = LogLogGroupList.logGroupList.add()
    LogGroup.contextFlow = "1"
    LogGroup.filename = "python.log"
    LogGroup.source = "localhost"
    
    LogTag = LogGroup.logTags.add()
    LogTag.key = "key"
    LogTag.value = "value"
    
    Log = LogGroup.logs.add()
    Log.time = int(round(time.time() * 1000000))
    
    Content = Log.contents.add()
    Content.key = "Hello"
    Content.value = "World"
    print(LogLogGroupList)
    # 序列化
    data = LogLogGroupList.SerializeToString()
    print(data)

    其实就是讲一个protobuf的结构文本序列化成了二进制的形式。

    反序列化

    反序列化就是将二进制转换成protobuf结构。

    # 反序列化
    LogLogGroupList = cls.LogGroupList()
    LogLogGroupList.ParseFromString(data)
    print(LogLogGroupList)

    运行结果

    上面序列化和反序列化代码结果运行如下:

    js