本文将介绍 Protobuf 序列化协议的使用方法。
协议上传
使用 Protobuf 协议需要用户上传 Proto 协议文件,压测引擎依赖协议文件完成请求的序列化。支持用户上传文件或目录,文件名需要保持唯一,同名文件将会被新上传的文件覆盖。如果用户上传 zip 文件,PTS 会解压文件,并展示解压后的文件结构。如果目录或者 zip 包中包含非 Proto 文件,PTS 将忽略这些文件。
说明:
借助您上传的 proto 文件,您可对脚本中的对象做序列化/反序列化。如果 demo.proto 依赖其他 proto 文件,那么也需要一并上传(谷歌提供的标准 proto 文件:google/protobuf/*.proto 不需要额外上传,PTS 会自动加载)。用户只需要加载主 pb 即可, 主 pb 依赖的其他 pb 文件,会自动递归加载。
示例
协议文件
duty.proto
syntax = "proto3";message Duty {string time = 1;string work = 2;}
student.proto
syntax = "proto3";import "duty.proto";package student;message Student {string name = 1;Gender gender = 2;message GradeInfo {enum Grade {DEFAULT = 0;FIRST = 1;SECOND = 2;THIRD = 3;}Grade grade = 1;}GradeInfo gradeInfo = 3;map<string, int32> scores = 4;repeated Duty duties = 5;}enum Gender {DEFAULT = 0;FEMALE = 1;MALE = 2;}message SearchRequest {string id = 1;}message SearchResponse {message Result {Student student = 1;}}service SearchService {rpc SearchScores (SearchRequest) returns (SearchResponse);}
脚本
import protobuf from 'pts/protobuf';// 加载协议文件根目录中的 student.proto,同时会加载 duty.protoprotobuf.load([], 'student.proto');// 加载中协议文件 dirName 目录中的 student.proto// protobuf.load(['dirName'], 'student.proto');export default function () {let bodyBuffer = protobuf.marshal('student.Student', {'name': 'Alice','gender': 1, // 或者 'FEMALE',enum 直接设置具体值即可'gradeInfo': {'grade': 'THIRD'},'scores': {'Chinese': 116,'Math': 120,'English': 106},'duties': [{'time': 'time1','work': 'work1'},{'time': 'time2','work': 'work2'}]});const value = protobuf.unmarshal('student.Student', bodyBuffer);// {"name":"Alice","gender":"FEMALE","gradeInfo":{"grade":"THIRD"},"scores":{"Math":120,"Chinese":116,"English":106},"duties":[{"time":"time","work":"work"}]}console.log(JSON.stringify(value));}