基於Netty的RPC架構實戰演練(六)-protocol buff學習使用

一,protocolbuffer簡介

protocolbuffer(以下簡稱PB)是google 的一種數據交換的格式,它獨立於語言,獨立於平臺。google 提供了多種語言的實現:java、c#c++、go 和 python,每一種實現都包含了相應語言的編譯器以及庫文件。它是一種協議,是谷歌推出的一種序列化協議,由於它是一種二進制的格式,比使用 xml 進行數據交換快許多。可以把它用於分佈式應用之間的數據通信或者異構環境下的數據交換。作爲一種效率和兼容性都很優秀的二進制數據傳輸格式,可以用於諸如網絡傳輸、配置文件、數據存儲等諸多領域。

二,protocolbuffer使用

1,首先準備protobuf-java-2.4.1.jar,protobuf-java-2.4.1-sources.jar,protoc.exe

2,編寫一個protocol的配置文件 ,類似於thift裏面的定義文件,如下所示,具體語法參考網絡

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;
}

3,準備build.bat執行命令,如下

protoc ./proto/*.proto --java_out=./src

pause

4,執行完成後生成的文件

// 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)
}

5,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())));
	}
}

三,Java本身序列化使用

定義一個實體對象,並且實現Serializable接口

package com.java;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 玩家對象
 * @author -琴獸-
 *
 */
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())));
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章