Protocol Buffer 使用-copy
概述
Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。
https://github.com/csy512889371/learndemo/tree/master/netty/ProtoTest
下面通过实验比较两者序列化后的字节数
protobuff:
[8, 101, 16, 20, 26, 5, 112, 101, 116, 101, 114, 32, -23, 7]
java:
[-84, -19, 0, 5, 115, 114, 0, 15, 99, 111, 109, 46, 106, 97, 118, 97, 46, 80, 108, 97, 121, 101, 114, -73, 43, 28, 39, -119, -86, -125, -3, 2, 0, 4, 73, 0, 3, 97, 103, 101, 74, 0, 8, 112, 108, 97, 121, 101, 114, 73, 100, 76, 0, 4, 110, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 76, 0, 6, 115, 107, 105, 108, 108, 115, 116, 0, 16, 76, 106, 97, 118, 97, 47, 117, 116, 105, 108, 47, 76, 105, 115, 116, 59, 120, 112, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 101, 116, 0, 5, 112, 101, 116, 101, 114, 115, 114, 0, 19, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 65, 114, 114, 97, 121, 76, 105, 115, 116, 120, -127, -46, 29, -103, -57, 97, -99, 3, 0, 1, 73, 0, 4, 115, 105, 122, 101, 120, 112, 0, 0, 0, 1, 119, 4, 0, 0, 0, 1, 115, 114, 0, 17, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 73, 110, 116, 101, 103, 101, 114, 18, -30, -96, -92, -9, -127, -121, 56, 2, 0, 1, 73, 0, 5, 118, 97, 108, 117, 101, 120, 114, 0, 16, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 78, 117, 109, 98, 101, 114, -122, -84, -107, 29, 11, -108, -32, -117, 2, 0, 0, 120, 112, 0, 0, 3, -23, 120]
例子
编写proto 配置
player.proto
option java_package = "com.proto";
option java_outer_classname = "PlayerModule";
message PBPlayer {
required int64 playerId = 1;
required int32 age = 2;
required string name = 3;
repeated int32 skills = 4;
}
message PBResource {
required int64 gold = 1;
required int32 energy = 2;
}
build.bat 使用protoc.exe 生成java代码
protoc ./proto/*.proto --java_out=./src
pause
生成的java代码如下
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/player.proto
package com.proto;
public final class PlayerModule {
private PlayerModule() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface PBPlayerOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required int64 playerId = 1;
boolean hasPlayerId();
long getPlayerId();
// required int32 age = 2;
boolean hasAge();
int getAge();
// required string name = 3;
boolean hasName();
String getName();
// repeated int32 skills = 4;
java.util.List<java.lang.Integer> getSkillsList();
int getSkillsCount();
int getSkills(int index);
}
public static final class PBPlayer extends
com.google.protobuf.GeneratedMessage
implements PBPlayerOrBuilder {
// Use PBPlayer.newBuilder() to construct.
private PBPlayer(Builder builder) {
super(builder);
}
private PBPlayer(boolean noInit) {}
private static final PBPlayer defaultInstance;
public static PBPlayer getDefaultInstance() {
return defaultInstance;
}
public PBPlayer getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.proto.PlayerModule.internal_static_PBPlayer_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.proto.PlayerModule.internal_static_PBPlayer_fieldAccessorTable;
}
private int bitField0_;
// required int64 playerId = 1;
public static final int PLAYERID_FIELD_NUMBER = 1;
private long playerId_;
public boolean hasPlayerId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public long getPlayerId() {
return playerId_;
}
// required int32 age = 2;
public static final int AGE_FIELD_NUMBER = 2;
private int age_;
public boolean hasAge() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getAge() {
return age_;
}
// required string name = 3;
public static final int NAME_FIELD_NUMBER = 3;
private java.lang.Object name_;
public boolean hasName() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public String getName() {
java.lang.Object ref = name_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (com.google.protobuf.Internal.isValidUtf8(bs)) {
name_ = s;
}
return s;
}
}
private com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// repeated int32 skills = 4;
public static final int SKILLS_FIELD_NUMBER = 4;
private java.util.List<java.lang.Integer> skills_;
public java.util.List<java.lang.Integer>
getSkillsList() {
return skills_;
}
public int getSkillsCount() {
return skills_.size();
}
public int getSkills(int index) {
return skills_.get(index);
}
private void initFields() {
playerId_ = 0L;
age_ = 0;
name_ = "";
skills_ = java.util.Collections.emptyList();;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasPlayerId()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasAge()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasName()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt64(1, playerId_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, age_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getNameBytes());
}
for (int i = 0; i < skills_.size(); i++) {
output.writeInt32(4, skills_.get(i));
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(1, playerId_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, age_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getNameBytes());
}
{
int dataSize = 0;
for (int i = 0; i < skills_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream
.computeInt32SizeNoTag(skills_.get(i));
}
size += dataSize;
size += 1 * getSkillsList().size();
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.proto.PlayerModule.PBPlayer parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.proto.PlayerModule.PBPlayer parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.proto.PlayerModule.PBPlayer parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.proto.PlayerModule.PBPlayer parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.proto.PlayerModule.PBPlayer parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.proto.PlayerModule.PBPlayer parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static com.proto.PlayerModule.PBPlayer parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.proto.PlayerModule.PBPlayer parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.proto.PlayerModule.PBPlayer parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.proto.PlayerModule.PBPlayer parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.proto.PlayerModule.PBPlayer prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.proto.PlayerModule.PBPlayerOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.proto.PlayerModule.internal_static_PBPlayer_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.proto.PlayerModule.internal_static_PBPlayer_fieldAccessorTable;
}
// Construct using com.proto.PlayerModule.PBPlayer.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
playerId_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
age_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
name_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
skills_ = java.util.Collections.emptyList();;
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.proto.PlayerModule.PBPlayer.getDescriptor();
}
public com.proto.PlayerModule.PBPlayer getDefaultInstanceForType() {
return com.proto.PlayerModule.PBPlayer.getDefaultInstance();
}
public com.proto.PlayerModule.PBPlayer build() {
com.proto.PlayerModule.PBPlayer result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private com.proto.PlayerModule.PBPlayer buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
com.proto.PlayerModule.PBPlayer result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public com.proto.PlayerModule.PBPlayer buildPartial() {
com.proto.PlayerModule.PBPlayer result = new com.proto.PlayerModule.PBPlayer(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.playerId_ = playerId_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.age_ = age_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.name_ = name_;
if (((bitField0_ & 0x00000008) == 0x00000008)) {
skills_ = java.util.Collections.unmodifiableList(skills_);
bitField0_ = (bitField0_ & ~0x00000008);
}
result.skills_ = skills_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.proto.PlayerModule.PBPlayer) {
return mergeFrom((com.proto.PlayerModule.PBPlayer)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.proto.PlayerModule.PBPlayer other) {
if (other == com.proto.PlayerModule.PBPlayer.getDefaultInstance()) return this;
if (other.hasPlayerId()) {
setPlayerId(other.getPlayerId());
}
if (other.hasAge()) {
setAge(other.getAge());
}
if (other.hasName()) {
setName(other.getName());
}
if (!other.skills_.isEmpty()) {
if (skills_.isEmpty()) {
skills_ = other.skills_;
bitField0_ = (bitField0_ & ~0x00000008);
} else {
ensureSkillsIsMutable();
skills_.addAll(other.skills_);
}
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasPlayerId()) {
return false;
}
if (!hasAge()) {
return false;
}
if (!hasName()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
playerId_ = input.readInt64();
break;
}
case 16: {
bitField0_ |= 0x00000002;
age_ = input.readInt32();
break;
}
case 26: {
bitField0_ |= 0x00000004;
name_ = input.readBytes();
break;
}
case 32: {
ensureSkillsIsMutable();
skills_.add(input.readInt32());
break;
}
case 34: {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
while (input.getBytesUntilLimit() > 0) {
addSkills(input.readInt32());
}
input.popLimit(limit);
break;
}
}
}
}
private int bitField0_;
// required int64 playerId = 1;
private long playerId_ ;
public boolean hasPlayerId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public long getPlayerId() {
return playerId_;
}
public Builder setPlayerId(long value) {
bitField0_ |= 0x00000001;
playerId_ = value;
onChanged();
return this;
}
public Builder clearPlayerId() {
bitField0_ = (bitField0_ & ~0x00000001);
playerId_ = 0L;
onChanged();
return this;
}
// required int32 age = 2;
private int age_ ;
public boolean hasAge() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getAge() {
return age_;
}
public Builder setAge(int value) {
bitField0_ |= 0x00000002;
age_ = value;
onChanged();
return this;
}
public Builder clearAge() {
bitField0_ = (bitField0_ & ~0x00000002);
age_ = 0;
onChanged();
return this;
}
// required string name = 3;
private java.lang.Object name_ = "";
public boolean hasName() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof String)) {
String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
name_ = s;
return s;
} else {
return (String) ref;
}
}
public Builder setName(String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
name_ = value;
onChanged();
return this;
}
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000004);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
void setName(com.google.protobuf.ByteString value) {
bitField0_ |= 0x00000004;
name_ = value;
onChanged();
}
// repeated int32 skills = 4;
private java.util.List<java.lang.Integer> skills_ = java.util.Collections.emptyList();;
private void ensureSkillsIsMutable() {
if (!((bitField0_ & 0x00000008) == 0x00000008)) {
skills_ = new java.util.ArrayList<java.lang.Integer>(skills_);
bitField0_ |= 0x00000008;
}
}
public java.util.List<java.lang.Integer>
getSkillsList() {
return java.util.Collections.unmodifiableList(skills_);
}
public int getSkillsCount() {
return skills_.size();
}
public int getSkills(int index) {
return skills_.get(index);
}
public Builder setSkills(
int index, int value) {
ensureSkillsIsMutable();
skills_.set(index, value);
onChanged();
return this;
}
public Builder addSkills(int value) {
ensureSkillsIsMutable();
skills_.add(value);
onChanged();
return this;
}
public Builder addAllSkills(
java.lang.Iterable<? extends java.lang.Integer> values) {
ensureSkillsIsMutable();
super.addAll(values, skills_);
onChanged();
return this;
}
public Builder clearSkills() {
skills_ = java.util.Collections.emptyList();;
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:PBPlayer)
}
static {
defaultInstance = new PBPlayer(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:PBPlayer)
}
public interface PBResourceOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required int64 gold = 1;
boolean hasGold();
long getGold();
// required int32 energy = 2;
boolean hasEnergy();
int getEnergy();
}
public static final class PBResource extends
com.google.protobuf.GeneratedMessage
implements PBResourceOrBuilder {
// Use PBResource.newBuilder() to construct.
private PBResource(Builder builder) {
super(builder);
}
private PBResource(boolean noInit) {}
private static final PBResource defaultInstance;
public static PBResource getDefaultInstance() {
return defaultInstance;
}
public PBResource getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.proto.PlayerModule.internal_static_PBResource_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.proto.PlayerModule.internal_static_PBResource_fieldAccessorTable;
}
private int bitField0_;
// required int64 gold = 1;
public static final int GOLD_FIELD_NUMBER = 1;
private long gold_;
public boolean hasGold() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public long getGold() {
return gold_;
}
// required int32 energy = 2;
public static final int ENERGY_FIELD_NUMBER = 2;
private int energy_;
public boolean hasEnergy() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getEnergy() {
return energy_;
}
private void initFields() {
gold_ = 0L;
energy_ = 0;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasGold()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasEnergy()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt64(1, gold_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, energy_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(1, gold_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, energy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.proto.PlayerModule.PBResource parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.proto.PlayerModule.PBResource parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.proto.PlayerModule.PBResource parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.proto.PlayerModule.PBResource parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.proto.PlayerModule.PBResource parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.proto.PlayerModule.PBResource parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static com.proto.PlayerModule.PBResource parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.proto.PlayerModule.PBResource parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.proto.PlayerModule.PBResource parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.proto.PlayerModule.PBResource parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.proto.PlayerModule.PBResource prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.proto.PlayerModule.PBResourceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.proto.PlayerModule.internal_static_PBResource_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.proto.PlayerModule.internal_static_PBResource_fieldAccessorTable;
}
// Construct using com.proto.PlayerModule.PBResource.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
gold_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
energy_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.proto.PlayerModule.PBResource.getDescriptor();
}
public com.proto.PlayerModule.PBResource getDefaultInstanceForType() {
return com.proto.PlayerModule.PBResource.getDefaultInstance();
}
public com.proto.PlayerModule.PBResource build() {
com.proto.PlayerModule.PBResource result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private com.proto.PlayerModule.PBResource buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
com.proto.PlayerModule.PBResource result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public com.proto.PlayerModule.PBResource buildPartial() {
com.proto.PlayerModule.PBResource result = new com.proto.PlayerModule.PBResource(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.gold_ = gold_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.energy_ = energy_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.proto.PlayerModule.PBResource) {
return mergeFrom((com.proto.PlayerModule.PBResource)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.proto.PlayerModule.PBResource other) {
if (other == com.proto.PlayerModule.PBResource.getDefaultInstance()) return this;
if (other.hasGold()) {
setGold(other.getGold());
}
if (other.hasEnergy()) {
setEnergy(other.getEnergy());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasGold()) {
return false;
}
if (!hasEnergy()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
gold_ = input.readInt64();
break;
}
case 16: {
bitField0_ |= 0x00000002;
energy_ = input.readInt32();
break;
}
}
}
}
private int bitField0_;
// required int64 gold = 1;
private long gold_ ;
public boolean hasGold() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public long getGold() {
return gold_;
}
public Builder setGold(long value) {
bitField0_ |= 0x00000001;
gold_ = value;
onChanged();
return this;
}
public Builder clearGold() {
bitField0_ = (bitField0_ & ~0x00000001);
gold_ = 0L;
onChanged();
return this;
}
// required int32 energy = 2;
private int energy_ ;
public boolean hasEnergy() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getEnergy() {
return energy_;
}
public Builder setEnergy(int value) {
bitField0_ |= 0x00000002;
energy_ = value;
onChanged();
return this;
}
public Builder clearEnergy() {
bitField0_ = (bitField0_ & ~0x00000002);
energy_ = 0;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:PBResource)
}
static {
defaultInstance = new PBResource(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:PBResource)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_PBPlayer_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_PBPlayer_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_PBResource_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_PBResource_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\022proto/player.proto\"G\n\010PBPlayer\022\020\n\010play" +
"erId\030\001 \002(\003\022\013\n\003age\030\002 \002(\005\022\014\n\004name\030\003 \002(\t\022\016\n" +
"\006skills\030\004 \003(\005\"*\n\nPBResource\022\014\n\004gold\030\001 \002(" +
"\003\022\016\n\006energy\030\002 \002(\005B\031\n\tcom.protoB\014PlayerMo" +
"dule"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_PBPlayer_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_PBPlayer_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_PBPlayer_descriptor,
new java.lang.String[] { "PlayerId", "Age", "Name", "Skills", },
com.proto.PlayerModule.PBPlayer.class,
com.proto.PlayerModule.PBPlayer.Builder.class);
internal_static_PBResource_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_PBResource_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_PBResource_descriptor,
new java.lang.String[] { "Gold", "Energy", },
com.proto.PlayerModule.PBResource.class,
com.proto.PlayerModule.PBResource.Builder.class);
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
使用protocol 序列化 和反序列化
package com.proto;
import java.util.Arrays;
import com.proto.PlayerModule.PBPlayer;
import com.proto.PlayerModule.PBPlayer.Builder;
/**
* protobuf学习
*
*
*/
public class PB2Bytes {
public static void main(String[] args) throws Exception {
byte[] bytes = toBytes();
toPlayer(bytes);
}
/**
* 序列化
*/
public static byte[] toBytes(){
//获取一个PBPlayer的构造器
Builder builder = PlayerModule.PBPlayer.newBuilder();
//设置数据
builder.setPlayerId(101).setAge(20).setName("peter").addSkills(1001);
//构造出对象
PBPlayer player = builder.build();
//序列化成字节数组
byte[] byteArray = player.toByteArray();
System.out.println(Arrays.toString(byteArray));
return byteArray;
}
/**
* 反序列化
* @param bs
* @throws Exception
*/
public static void toPlayer(byte[] bs) throws Exception{
PBPlayer player = PlayerModule.PBPlayer.parseFrom(bs);
System.out.println("playerId:" + player.getPlayerId());
System.out.println("age:" + player.getAge());
System.out.println("name:" + player.getName());
System.out.println("skills:" + (Arrays.toString(player.getSkillsList().toArray())));
}
}
序列号后的对象大小
[8, 101, 16, 20, 26, 5, 112, 101, 116, 101, 114, 32, -23, 7]
java 实现虚拟化与反序列化
package com.java;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 玩家对象
*
*
*/
public class Player implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5248069984631225347L;
public Player(long playerId, int age, String name) {
this.playerId = playerId;
this.age = age;
this.name = name;
}
private long playerId;
private int age;
private String name;
private List<Integer> skills = new ArrayList<>();
public long getPlayerId() {
return playerId;
}
public void setPlayerId(long playerId) {
this.playerId = playerId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Integer> getSkills() {
return skills;
}
public void setSkills(List<Integer> skills) {
this.skills = skills;
}
}
package com.java;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
public class JAVA2Bytes {
public static void main(String[] args) throws Exception {
byte[] bytes = toBytes();
toPlayer(bytes);
}
/**
* 序列化
* @throws IOException
*/
public static byte[] toBytes() throws IOException{
Player player = new Player(101, 20, "peter");
player.getSkills().add(1001);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
//写入对象
objectOutputStream.writeObject(player);
//获取 字节数组
byte[] byteArray = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(byteArray));
return byteArray;
}
/**
* 反序列化
* @param bs
* @throws Exception
*/
public static void toPlayer(byte[] bs) throws Exception{
ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(bs));
Player player = (Player)inputStream.readObject();
//打印
System.out.println("playerId:" + player.getPlayerId());
System.out.println("age:" + player.getAge());
System.out.println("name:" + player.getName());
System.out.println("skills:" + (Arrays.toString(player.getSkills().toArray())));
}
————————————————
版权声明:本文为CSDN博主「chenshiying007」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_27384769/article/details/80694205
Protocol Buffer 使用-copy的更多相关文章
- cocos2d-x protobuf; cocos2dx protocol buffer
昨天了解到项目要用到protocol buffer,今天晚上看了一下,了解protobuf本质上就是一个信息表达协议+编辑,解析库. linux开源软件都一个模式,先./configure --hel ...
- Protocol Buffer搭建及示例
本文来源:http://www.tanhao.me/code/150911.html/ Protocol Buffer(简称Protobuf或PB)是由Google推出的一种数据交换格式,与传统的XM ...
- 从零开始山寨Caffe·伍:Protocol Buffer简易指南
你为Class外访问private对象而苦恼嘛?你为设计序列化格式而头疼嘛? ——欢迎体验Google Protocol Buffer 面向对象之封装性 历史遗留问题 面向对象中最矛盾的一个特性,就是 ...
- [原创翻译]Protocol Buffer Basics: C#
Protocol Buffer 基础知识:c# 原文地址:https://developers.google.com/protocol-buffers/docs/csharptutorial ...
- Google Protocol Buffer 的使用和原理[转]
本文转自: http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/ Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构 ...
- Google Protocol Buffer 的使用
简介 Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 48,162 种报文格式定义和超过 12,183 ...
- 学习Google Protocol buffer之语法
上一篇结尾的时候问了几个问题,其实主要就是这个protoBuffer协议的语法,弄清楚语法后边才好开展工作嘛,不然大眼而对小眼儿,互相不认识,就没法玩耍了.其实就是学习怎么用google提供的这套 p ...
- 学习Google Protocol buffer之概述
XML这种属于非常强大的一种格式,能存储任何你想存的数据,而且编辑起来还是比较方便的.致命的缺陷在于比较庞大,在某些情况下,序列化和解析都会成为瓶颈.这种对于实时性很强的应用来说,就不太适合了,想象下 ...
- Google Protocol Buffer 简单介绍
以下内容主要整理自官方文档. 为什么使用 Protocol Buffers .proto文件 Protocol Buffers 语法 编译.proto文件 Protocol Buffers API 枚 ...
- Ggoogle Protocol Buffer的使用 (基于C++语言)
首先说明的是Protocol Buffle是灵活高效的.它的一个很好的优点(很重要的,我认为)就是后向兼容性--当我们扩展了了.proto文件后,我们照样可以用它来读取之前生成的文件. 之前已经写了关 ...
随机推荐
- 关于Java后台处理前端用户传来数据过大,超过数据库字段设置长度导致的异常问题处理
在DTO bean对象上使用javax验证(如最小值,最大值等,请参阅here).
- Python安装技术类库模块
方法1: 方法2: 用如下命令安装即可(注意都得是英文字符): # 简单粗暴,但是可能安装到了不同的环境 pip install some-package # 复杂但是精准还快速 C:\Python3 ...
- 8.Jenkins+Docker+SpringCloud微服务持续集成
前言 通过前几章的学习,了解了持续集成概念以及相关技术的学习和使用 接下来学习构建一整套SpringCloud微服务+Docker+Jenkins的持续集成案例 环境 架构图 流程说明: 开发人员将代 ...
- php 异步并行
如果你有一批数据需要调用远程接口处理,而远程接口处理时间很长,比如需要1秒左右,那10条数据就是10秒,你的程序就要10S才能结束,而这样的话一旦接口提供方有点问题,就需要20秒 30秒甚至更久,这样 ...
- linux history 想显示历史命令的时间和作者
vi ~/.profile 增加 HISTTIMEFORMAT="%F %T `whoami` `who am i|awk '{print $1,$5}'|sed 's/ (/@/'|sed ...
- nodejs版本管理工具之nvm
有时候 项目中依赖不同版本的node,这就需要我们使用一个版本管理工具 有序的管理这些node,这里介绍使用nvm GitHub地址:https://github.com/nvm-sh/nvm 前提: ...
- 如何用Docker Compose部署项目?
目录 前言 Docker Compose 1. Docker Compose是什么? 2. Docker Compose 的具体步骤 3. 如何在IDEA项目里面使用Docker Compose 启动 ...
- Mybatis【19】-- Mybatis自关联多对多查询
注:代码已托管在GitHub上,地址是:https://github.com/Damaer/Mybatis-Learning ,项目是mybatis-15-oneself-many2many,需要自取 ...
- 【Java基础】-- instanceof 用法详解
1. instanceof关键字 如果你之前一直没有怎么仔细了解过instanceof关键字,现在就来了解一下: instanceof其实是java的一个二元操作符,和=,<,>这些是类似 ...
- HUAWEI SECURITY 2023 山东大学专场 WP
Crypto by Smera1d0 1.ezrsa 题干如下: from Crypto.Util.number import getPrime from secret import flag p = ...