背景
博主最近在研究sofa-jraft的时候,看到jraft使用的protobuf,所以单独拎出来单独理解一下。
Protobuf语法
https://www.cnblogs.com/resentment/p/6539021.html
使用案例
1 添加proto文件
syntax="proto2"; package jraft; import "enum.proto"; option java_package="com.alipay.sofa.jraft.entity1"; option java_outer_classname = "RaftOutter1"; message EntryMeta { required int64 term = 1; required EntryType type = 2; repeated string peers = 3; optional int64 data_len = 4; // Don‘t change field id of `old_peers‘ in the consideration of backward // compatibility repeated string old_peers = 5; // Checksum fot this log entry, since 1.2.6, added by boyan@antfin.com optional int64 checksum = 6; repeated string learners = 7; repeated string old_learners = 8; }; message SnapshotMeta { required int64 last_included_index = 1; required int64 last_included_term = 2; repeated string peers = 3; repeated string old_peers = 4; repeated string learners = 5; repeated string old_learners = 6; }
2 下载protoc.exe 执行:
protoc ./raft.proto --java_out=../java/
会看到在entity1目录下生成
3 测试
package com.alipay.sofa.jraft.entity1; import com.alipay.sofa.jraft.entity.EnumOutter; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Arrays; public class PB2Byte { public static void main(String[] args) throws InvalidProtocolBufferException { RaftOutter1.EntryMeta.Builder builder = RaftOutter1.EntryMeta.newBuilder(); // ====================================赋值================================ builder.setType(EnumOutter.EntryType.ENTRY_TYPE_UNKNOWN); builder.setChecksum(4354734L); builder.setTerm(1); // builder.setPeers(0, "1"); builder.addPeers("gdghfhf"); builder.addOldPeers("gdghfhf1"); builder.addLearners("7"); builder.addOldLearners("8"); // ====================================build对象================================ RaftOutter1.EntryMeta entryMeta = builder.build(); // ====================================对象序列化================================ byte[] byteArray = entryMeta.toByteArray(); System.out.println(Arrays.toString(byteArray)); // ====================================反序列化================================ RaftOutter1.EntryMeta newEntryMeta = RaftOutter1.EntryMeta.parseFrom(byteArray); System.out.println("newEntryMeta:" + newEntryMeta.toString()); } }
4 结果