本文记录protobuf3的基础使用实例:
使用protobuf3在 java 端进行对象序列化到文件,在python端从文件读取并反序列化成python对象
1.环境准备
Notation:错误的产生一般来源于环境版本不匹配
>python --version Python 3.9.2 >protoc --version libprotoc 3.12.1 >java -version openjdk version "14" 2020-03-17 OpenJDK Runtime Environment (build 14+36-1461) OpenJDK 64-Bit Server VM (build 14+36-1461, mixed mode, sharing)
>pip show protobuf
Name: protobuf
Version: 3.15.3
2. 编码实现
1. 编写proto文件 simple.proto
syntax = "proto3"; message SearchRequest { string query = 1; int32 page_number = 2; int32 result_per_page = 3; }
2. 生成 java 及 python 文件
>protoc --java_out=./ simple.proto
>protoc --python_out=./ simple.proto
3. 使用 java 创建 SearchRequest对象,并序列化到文件 simple.data
import java.io.FileOutputStream; import java.io.IOException; public class App { public static void main(String[] args) throws IOException { Simple.SearchRequest searchRequest = Simple.SearchRequest.newBuilder().setQuery("searchName").setPageNumber(1).setResultPerPage(10).build(); searchRequest.writeTo(new FileOutputStream("simple.data")); System.out.println("write over"); } }
4. 使用 python 从文件simple.data中读取流,并反序列化得到python的SearchRequest对象
# -*- coding: utf-8 -*- from simple_pb2 import SearchRequest if __name__ == '__main__': f = open("simple.data", "r") re = SearchRequest() re.ParseFromString(f.read().encode("utf-8")) print(re)
反序列化结果如下
query: "searchName" page_number: 1 result_per_page: 10