《精通并发与Netty》学习笔记(05

protobuf是由Google开发的一套对数据结构进行序列化的方法,可用做通信协议,数据存储格式,等等。其特点是不限语言、不限平台、扩展性强

 Netty也提供了对Protobuf的天然支持,我们今天就写一个简单的示例,简单地了解一下Netty对Google的protoBuf的支持

场景设置:

 我们的示例场景很简单的:客户端发送一个信息,这个信息用Protobuf来做序列化,然后服务器端接收这个信息,解码,读取信息

protobuf与xml,json这样的数据格式一样,都有自己的一套语法,且语法很简单,很容易掌握,xml文件的后缀名是xml,json的后缀名是json,以此类推,那么protobuf的后缀名就是proto

关于proto的基本语法与Java的bean很像,详细可以参考官网,可以看下这篇博客:http://blog.sina.com.cn/s/blog_9b0604b40101qm35.html

第一步:定义proto文件
现在我们定义一个类似Java bean的proto文件,我们定义一个“富人”类,他有多辆车,我们先按照语法,写一个RichMan.proto,如下面的代码清单所示:

package netty;  
  
option java_package = "com.lyncc.netty.codec.protobuf.demo";  
option java_outer_classname = "RichManProto";  
  
message RichMan {  
  
   required int32 id = 1;  
   required string name = 2;  
   optional string email = 3;  
     
   enum CarType {  
     AUDI = 0;  
     BENZ = 1;  
     LAMBORGHINI = 2;  
     DASAUTO = 3;  
   }  
     
   message Car {  
      required string name = 1;  
      optional CarType type = 2 [default = BENZ];  
   }  
     
   repeated Car cars = 4;  
     
}  

 给出上面代码的一些基本解释:

1)java_package值得是该文件生成的java文件的包路径
2)java_outer_classname值的是生成的class的名称
3)message和enum是它的基本类型,很类似于java的class和枚举
4)required表名这个字段是必须的,option表明这个字段可选,default表明这个字段有默认值
5)repeat表明这个字段可以重复,类似于java中的List,该例子中Car的声明中,就相当于java中的List<Car>
6)每个声明的后面的数字,例如1,2,3, 4等等,同级的声明不能重复
总而言之,这个“类”定义了一个富人,该富人有id,名称,邮箱,而且该富人有多个名车,这些名车的类型有奥迪,奔驰,兰博基尼,大众
好了,到目前为止,proto我们已经定义好了,Google提供了一个类似脚本的工具,可以使我们将proto文件转化成java文件

第二步:将proto文件转化成java文件(参考上节)

将生成的文件拷贝至项目中,参考生成文件如下:

// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: RichMan.proto

package com.ssy.netty.proto;

public final class RichManProto {
  private RichManProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  public interface RichManOrBuilder extends
      // @@protoc_insertion_point(interface_extends:RichMan)
      com.google.protobuf.MessageOrBuilder {

    /**
     * <code>required int32 id = 1;</code>
     */
    boolean hasId();
    /**
     * <code>required int32 id = 1;</code>
     */
    int getId();

    /**
     * <code>required string name = 2;</code>
     */
    boolean hasName();
    /**
     * <code>required string name = 2;</code>
     */
    String getName();
    /**
     * <code>required string name = 2;</code>
     */
    com.google.protobuf.ByteString
        getNameBytes();

    /**
     * <code>optional string email = 3;</code>
     */
    boolean hasEmail();
    /**
     * <code>optional string email = 3;</code>
     */
    String getEmail();
    /**
     * <code>optional string email = 3;</code>
     */
    com.google.protobuf.ByteString
        getEmailBytes();

    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    java.util.List<RichMan.Car>
        getCarsList();
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    RichMan.Car getCars(int index);
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    int getCarsCount();
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    java.util.List<? extends RichMan.CarOrBuilder>
        getCarsOrBuilderList();
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    RichMan.CarOrBuilder getCarsOrBuilder(
            int index);
  }
  /**
   * Protobuf type {@code RichMan}
   */
  public  static final class RichMan extends
      com.google.protobuf.GeneratedMessageV3 implements
      // @@protoc_insertion_point(message_implements:RichMan)
      RichManOrBuilder {
  private static final long serialVersionUID = 0L;
    // Use RichMan.newBuilder() to construct.
    private RichMan(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
      super(builder);
    }
    private RichMan() {
      name_ = "";
      email_ = "";
      cars_ = java.util.Collections.emptyList();
    }

    @Override
    public final com.google.protobuf.UnknownFieldSet
    getUnknownFields() {
      return this.unknownFields;
    }
    private RichMan(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      this();
      if (extensionRegistry == null) {
        throw new NullPointerException();
      }
      int mutable_bitField0_ = 0;
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder();
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            case 8: {
              bitField0_ |= 0x00000001;
              id_ = input.readInt32();
              break;
            }
            case 18: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000002;
              name_ = bs;
              break;
            }
            case 26: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000004;
              email_ = bs;
              break;
            }
            case 34: {
              if (!((mutable_bitField0_ & 0x00000008) != 0)) {
                cars_ = new java.util.ArrayList<Car>();
                mutable_bitField0_ |= 0x00000008;
              }
              cars_.add(
                  input.readMessage(Car.PARSER, extensionRegistry));
              break;
            }
            default: {
              if (!parseUnknownField(
                  input, unknownFields, extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e).setUnfinishedMessage(this);
      } finally {
        if (((mutable_bitField0_ & 0x00000008) != 0)) {
          cars_ = java.util.Collections.unmodifiableList(cars_);
        }
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return RichManProto.internal_static_RichMan_descriptor;
    }

    @Override
    protected FieldAccessorTable
        internalGetFieldAccessorTable() {
      return RichManProto.internal_static_RichMan_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              RichMan.class, Builder.class);
    }

    /**
     * Protobuf enum {@code RichMan.CarType}
     */
    public enum CarType
        implements com.google.protobuf.ProtocolMessageEnum {
      /**
       * <code>AUDI = 0;</code>
       */
      AUDI(0),
      /**
       * <code>BENZ = 1;</code>
       */
      BENZ(1),
      /**
       * <code>LAMBORGHINI = 2;</code>
       */
      LAMBORGHINI(2),
      /**
       * <code>DASAUTO = 3;</code>
       */
      DASAUTO(3),
      ;

      /**
       * <code>AUDI = 0;</code>
       */
      public static final int AUDI_VALUE = 0;
      /**
       * <code>BENZ = 1;</code>
       */
      public static final int BENZ_VALUE = 1;
      /**
       * <code>LAMBORGHINI = 2;</code>
       */
      public static final int LAMBORGHINI_VALUE = 2;
      /**
       * <code>DASAUTO = 3;</code>
       */
      public static final int DASAUTO_VALUE = 3;


      public final int getNumber() {
        return value;
      }

      /**
       * @deprecated Use {@link #forNumber(int)} instead.
       */
      @Deprecated
      public static CarType valueOf(int value) {
        return forNumber(value);
      }

      public static CarType forNumber(int value) {
        switch (value) {
          case 0: return AUDI;
          case 1: return BENZ;
          case 2: return LAMBORGHINI;
          case 3: return DASAUTO;
          default: return null;
        }
      }

      public static com.google.protobuf.Internal.EnumLiteMap<CarType>
          internalGetValueMap() {
        return internalValueMap;
      }
      private static final com.google.protobuf.Internal.EnumLiteMap<
          CarType> internalValueMap =
            new com.google.protobuf.Internal.EnumLiteMap<CarType>() {
              public CarType findValueByNumber(int number) {
                return CarType.forNumber(number);
              }
            };

      public final com.google.protobuf.Descriptors.EnumValueDescriptor
          getValueDescriptor() {
        return getDescriptor().getValues().get(ordinal());
      }
      public final com.google.protobuf.Descriptors.EnumDescriptor
          getDescriptorForType() {
        return getDescriptor();
      }
      public static final com.google.protobuf.Descriptors.EnumDescriptor
          getDescriptor() {
        return RichMan.getDescriptor().getEnumTypes().get(0);
      }

      private static final CarType[] VALUES = values();

      public static CarType valueOf(
          com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
        if (desc.getType() != getDescriptor()) {
          throw new IllegalArgumentException(
            "EnumValueDescriptor is not for this type.");
        }
        return VALUES[desc.getIndex()];
      }

      private final int value;

      private CarType(int value) {
        this.value = value;
      }

      // @@protoc_insertion_point(enum_scope:RichMan.CarType)
    }

    public interface CarOrBuilder extends
        // @@protoc_insertion_point(interface_extends:RichMan.Car)
        com.google.protobuf.MessageOrBuilder {

      /**
       * <code>required string name = 1;</code>
       */
      boolean hasName();
      /**
       * <code>required string name = 1;</code>
       */
      String getName();
      /**
       * <code>required string name = 1;</code>
       */
      com.google.protobuf.ByteString
          getNameBytes();

      /**
       * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
       */
      boolean hasType();
      /**
       * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
       */
      CarType getType();
    }
    /**
     * Protobuf type {@code RichMan.Car}
     */
    public  static final class Car extends
        com.google.protobuf.GeneratedMessageV3 implements
        // @@protoc_insertion_point(message_implements:RichMan.Car)
        CarOrBuilder {
    private static final long serialVersionUID = 0L;
      // Use Car.newBuilder() to construct.
      private Car(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
        super(builder);
      }
      private Car() {
        name_ = "";
        type_ = 1;
      }

      @Override
      public final com.google.protobuf.UnknownFieldSet
      getUnknownFields() {
        return this.unknownFields;
      }
      private Car(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        this();
        if (extensionRegistry == null) {
          throw new NullPointerException();
        }
        int mutable_bitField0_ = 0;
        com.google.protobuf.UnknownFieldSet.Builder unknownFields =
            com.google.protobuf.UnknownFieldSet.newBuilder();
        try {
          boolean done = false;
          while (!done) {
            int tag = input.readTag();
            switch (tag) {
              case 0:
                done = true;
                break;
              case 10: {
                com.google.protobuf.ByteString bs = input.readBytes();
                bitField0_ |= 0x00000001;
                name_ = bs;
                break;
              }
              case 16: {
                int rawValue = input.readEnum();
                  @SuppressWarnings("deprecation")
                CarType value = CarType.valueOf(rawValue);
                if (value == null) {
                  unknownFields.mergeVarintField(2, rawValue);
                } else {
                  bitField0_ |= 0x00000002;
                  type_ = rawValue;
                }
                break;
              }
              default: {
                if (!parseUnknownField(
                    input, unknownFields, extensionRegistry, tag)) {
                  done = true;
                }
                break;
              }
            }
          }
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          throw e.setUnfinishedMessage(this);
        } catch (java.io.IOException e) {
          throw new com.google.protobuf.InvalidProtocolBufferException(
              e).setUnfinishedMessage(this);
        } finally {
          this.unknownFields = unknownFields.build();
          makeExtensionsImmutable();
        }
      }
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return RichManProto.internal_static_RichMan_Car_descriptor;
      }

      @Override
      protected FieldAccessorTable
          internalGetFieldAccessorTable() {
        return RichManProto.internal_static_RichMan_Car_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                Car.class, Builder.class);
      }

      private int bitField0_;
      public static final int NAME_FIELD_NUMBER = 1;
      private volatile Object name_;
      /**
       * <code>required string name = 1;</code>
       */
      public boolean hasName() {
        return ((bitField0_ & 0x00000001) != 0);
      }
      /**
       * <code>required string name = 1;</code>
       */
      public String getName() {
        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 (bs.isValidUtf8()) {
            name_ = s;
          }
          return s;
        }
      }
      /**
       * <code>required string name = 1;</code>
       */
      public com.google.protobuf.ByteString
          getNameBytes() {
        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;
        }
      }

      public static final int TYPE_FIELD_NUMBER = 2;
      private int type_;
      /**
       * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
       */
      public boolean hasType() {
        return ((bitField0_ & 0x00000002) != 0);
      }
      /**
       * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
       */
      public CarType getType() {
        @SuppressWarnings("deprecation")
        CarType result = CarType.valueOf(type_);
        return result == null ? CarType.BENZ : result;
      }

      private byte memoizedIsInitialized = -1;
      @Override
      public final boolean isInitialized() {
        byte isInitialized = memoizedIsInitialized;
        if (isInitialized == 1) return true;
        if (isInitialized == 0) return false;

        if (!hasName()) {
          memoizedIsInitialized = 0;
          return false;
        }
        memoizedIsInitialized = 1;
        return true;
      }

      @Override
      public void writeTo(com.google.protobuf.CodedOutputStream output)
                          throws java.io.IOException {
        if (((bitField0_ & 0x00000001) != 0)) {
          com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
        }
        if (((bitField0_ & 0x00000002) != 0)) {
          output.writeEnum(2, type_);
        }
        unknownFields.writeTo(output);
      }

      @Override
      public int getSerializedSize() {
        int size = memoizedSize;
        if (size != -1) return size;

        size = 0;
        if (((bitField0_ & 0x00000001) != 0)) {
          size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
        }
        if (((bitField0_ & 0x00000002) != 0)) {
          size += com.google.protobuf.CodedOutputStream
            .computeEnumSize(2, type_);
        }
        size += unknownFields.getSerializedSize();
        memoizedSize = size;
        return size;
      }

      @Override
      public boolean equals(final Object obj) {
        if (obj == this) {
         return true;
        }
        if (!(obj instanceof Car)) {
          return super.equals(obj);
        }
        Car other = (Car) obj;

        if (hasName() != other.hasName()) return false;
        if (hasName()) {
          if (!getName()
              .equals(other.getName())) return false;
        }
        if (hasType() != other.hasType()) return false;
        if (hasType()) {
          if (type_ != other.type_) return false;
        }
        if (!unknownFields.equals(other.unknownFields)) return false;
        return true;
      }

      @Override
      public int hashCode() {
        if (memoizedHashCode != 0) {
          return memoizedHashCode;
        }
        int hash = 41;
        hash = (19 * hash) + getDescriptor().hashCode();
        if (hasName()) {
          hash = (37 * hash) + NAME_FIELD_NUMBER;
          hash = (53 * hash) + getName().hashCode();
        }
        if (hasType()) {
          hash = (37 * hash) + TYPE_FIELD_NUMBER;
          hash = (53 * hash) + type_;
        }
        hash = (29 * hash) + unknownFields.hashCode();
        memoizedHashCode = hash;
        return hash;
      }

      public static Car parseFrom(
          java.nio.ByteBuffer data)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return PARSER.parseFrom(data);
      }
      public static Car parseFrom(
          java.nio.ByteBuffer data,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return PARSER.parseFrom(data, extensionRegistry);
      }
      public static Car parseFrom(
          com.google.protobuf.ByteString data)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return PARSER.parseFrom(data);
      }
      public static Car parseFrom(
          com.google.protobuf.ByteString data,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return PARSER.parseFrom(data, extensionRegistry);
      }
      public static Car parseFrom(byte[] data)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return PARSER.parseFrom(data);
      }
      public static Car parseFrom(
          byte[] data,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return PARSER.parseFrom(data, extensionRegistry);
      }
      public static Car parseFrom(java.io.InputStream input)
          throws java.io.IOException {
        return com.google.protobuf.GeneratedMessageV3
            .parseWithIOException(PARSER, input);
      }
      public static Car parseFrom(
          java.io.InputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        return com.google.protobuf.GeneratedMessageV3
            .parseWithIOException(PARSER, input, extensionRegistry);
      }
      public static Car parseDelimitedFrom(java.io.InputStream input)
          throws java.io.IOException {
        return com.google.protobuf.GeneratedMessageV3
            .parseDelimitedWithIOException(PARSER, input);
      }
      public static Car parseDelimitedFrom(
          java.io.InputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        return com.google.protobuf.GeneratedMessageV3
            .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
      }
      public static Car parseFrom(
          com.google.protobuf.CodedInputStream input)
          throws java.io.IOException {
        return com.google.protobuf.GeneratedMessageV3
            .parseWithIOException(PARSER, input);
      }
      public static Car parseFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        return com.google.protobuf.GeneratedMessageV3
            .parseWithIOException(PARSER, input, extensionRegistry);
      }

      @Override
      public Builder newBuilderForType() { return newBuilder(); }
      public static Builder newBuilder() {
        return DEFAULT_INSTANCE.toBuilder();
      }
      public static Builder newBuilder(Car prototype) {
        return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
      }
      @Override
      public Builder toBuilder() {
        return this == DEFAULT_INSTANCE
            ? new Builder() : new Builder().mergeFrom(this);
      }

      @Override
      protected Builder newBuilderForType(
          BuilderParent parent) {
        Builder builder = new Builder(parent);
        return builder;
      }
      /**
       * Protobuf type {@code RichMan.Car}
       */
      public static final class Builder extends
          com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
          // @@protoc_insertion_point(builder_implements:RichMan.Car)
          CarOrBuilder {
        public static final com.google.protobuf.Descriptors.Descriptor
            getDescriptor() {
          return RichManProto.internal_static_RichMan_Car_descriptor;
        }

        @Override
        protected FieldAccessorTable
            internalGetFieldAccessorTable() {
          return RichManProto.internal_static_RichMan_Car_fieldAccessorTable
              .ensureFieldAccessorsInitialized(
                  Car.class, Builder.class);
        }

        // Construct using com.ssy.netty.proto.RichManProto.RichMan.Car.newBuilder()
        private Builder() {
          maybeForceBuilderInitialization();
        }

        private Builder(
            BuilderParent parent) {
          super(parent);
          maybeForceBuilderInitialization();
        }
        private void maybeForceBuilderInitialization() {
          if (com.google.protobuf.GeneratedMessageV3
                  .alwaysUseFieldBuilders) {
          }
        }
        @Override
        public Builder clear() {
          super.clear();
          name_ = "";
          bitField0_ = (bitField0_ & ~0x00000001);
          type_ = 1;
          bitField0_ = (bitField0_ & ~0x00000002);
          return this;
        }

        @Override
        public com.google.protobuf.Descriptors.Descriptor
            getDescriptorForType() {
          return RichManProto.internal_static_RichMan_Car_descriptor;
        }

        @Override
        public Car getDefaultInstanceForType() {
          return Car.getDefaultInstance();
        }

        @Override
        public Car build() {
          Car result = buildPartial();
          if (!result.isInitialized()) {
            throw newUninitializedMessageException(result);
          }
          return result;
        }

        @Override
        public Car buildPartial() {
          Car result = new Car(this);
          int from_bitField0_ = bitField0_;
          int to_bitField0_ = 0;
          if (((from_bitField0_ & 0x00000001) != 0)) {
            to_bitField0_ |= 0x00000001;
          }
          result.name_ = name_;
          if (((from_bitField0_ & 0x00000002) != 0)) {
            to_bitField0_ |= 0x00000002;
          }
          result.type_ = type_;
          result.bitField0_ = to_bitField0_;
          onBuilt();
          return result;
        }

        @Override
        public Builder clone() {
          return super.clone();
        }
        @Override
        public Builder setField(
            com.google.protobuf.Descriptors.FieldDescriptor field,
            Object value) {
          return super.setField(field, value);
        }
        @Override
        public Builder clearField(
            com.google.protobuf.Descriptors.FieldDescriptor field) {
          return super.clearField(field);
        }
        @Override
        public Builder clearOneof(
            com.google.protobuf.Descriptors.OneofDescriptor oneof) {
          return super.clearOneof(oneof);
        }
        @Override
        public Builder setRepeatedField(
            com.google.protobuf.Descriptors.FieldDescriptor field,
            int index, Object value) {
          return super.setRepeatedField(field, index, value);
        }
        @Override
        public Builder addRepeatedField(
            com.google.protobuf.Descriptors.FieldDescriptor field,
            Object value) {
          return super.addRepeatedField(field, value);
        }
        @Override
        public Builder mergeFrom(com.google.protobuf.Message other) {
          if (other instanceof Car) {
            return mergeFrom((Car)other);
          } else {
            super.mergeFrom(other);
            return this;
          }
        }

        public Builder mergeFrom(Car other) {
          if (other == Car.getDefaultInstance()) return this;
          if (other.hasName()) {
            bitField0_ |= 0x00000001;
            name_ = other.name_;
            onChanged();
          }
          if (other.hasType()) {
            setType(other.getType());
          }
          this.mergeUnknownFields(other.unknownFields);
          onChanged();
          return this;
        }

        @Override
        public final boolean isInitialized() {
          if (!hasName()) {
            return false;
          }
          return true;
        }

        @Override
        public Builder mergeFrom(
            com.google.protobuf.CodedInputStream input,
            com.google.protobuf.ExtensionRegistryLite extensionRegistry)
            throws java.io.IOException {
          Car parsedMessage = null;
          try {
            parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
          } catch (com.google.protobuf.InvalidProtocolBufferException e) {
            parsedMessage = (Car) e.getUnfinishedMessage();
            throw e.unwrapIOException();
          } finally {
            if (parsedMessage != null) {
              mergeFrom(parsedMessage);
            }
          }
          return this;
        }
        private int bitField0_;

        private Object name_ = "";
        /**
         * <code>required string name = 1;</code>
         */
        public boolean hasName() {
          return ((bitField0_ & 0x00000001) != 0);
        }
        /**
         * <code>required string name = 1;</code>
         */
        public String getName() {
          Object ref = name_;
          if (!(ref instanceof String)) {
            com.google.protobuf.ByteString bs =
                (com.google.protobuf.ByteString) ref;
            String s = bs.toStringUtf8();
            if (bs.isValidUtf8()) {
              name_ = s;
            }
            return s;
          } else {
            return (String) ref;
          }
        }
        /**
         * <code>required string name = 1;</code>
         */
        public com.google.protobuf.ByteString
            getNameBytes() {
          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;
          }
        }
        /**
         * <code>required string name = 1;</code>
         */
        public Builder setName(
            String value) {
          if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
          name_ = value;
          onChanged();
          return this;
        }
        /**
         * <code>required string name = 1;</code>
         */
        public Builder clearName() {
          bitField0_ = (bitField0_ & ~0x00000001);
          name_ = getDefaultInstance().getName();
          onChanged();
          return this;
        }
        /**
         * <code>required string name = 1;</code>
         */
        public Builder setNameBytes(
            com.google.protobuf.ByteString value) {
          if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
          name_ = value;
          onChanged();
          return this;
        }

        private int type_ = 1;
        /**
         * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
         */
        public boolean hasType() {
          return ((bitField0_ & 0x00000002) != 0);
        }
        /**
         * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
         */
        public CarType getType() {
          @SuppressWarnings("deprecation")
          CarType result = CarType.valueOf(type_);
          return result == null ? CarType.BENZ : result;
        }
        /**
         * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
         */
        public Builder setType(CarType value) {
          if (value == null) {
            throw new NullPointerException();
          }
          bitField0_ |= 0x00000002;
          type_ = value.getNumber();
          onChanged();
          return this;
        }
        /**
         * <code>optional .RichMan.CarType type = 2 [default = BENZ];</code>
         */
        public Builder clearType() {
          bitField0_ = (bitField0_ & ~0x00000002);
          type_ = 1;
          onChanged();
          return this;
        }
        @Override
        public final Builder setUnknownFields(
            final com.google.protobuf.UnknownFieldSet unknownFields) {
          return super.setUnknownFields(unknownFields);
        }

        @Override
        public final Builder mergeUnknownFields(
            final com.google.protobuf.UnknownFieldSet unknownFields) {
          return super.mergeUnknownFields(unknownFields);
        }


        // @@protoc_insertion_point(builder_scope:RichMan.Car)
      }

      // @@protoc_insertion_point(class_scope:RichMan.Car)
      private static final Car DEFAULT_INSTANCE;
      static {
        DEFAULT_INSTANCE = new Car();
      }

      public static Car getDefaultInstance() {
        return DEFAULT_INSTANCE;
      }

      @Deprecated public static final com.google.protobuf.Parser<Car>
          PARSER = new com.google.protobuf.AbstractParser<Car>() {
        @Override
        public Car parsePartialFrom(
            com.google.protobuf.CodedInputStream input,
            com.google.protobuf.ExtensionRegistryLite extensionRegistry)
            throws com.google.protobuf.InvalidProtocolBufferException {
          return new Car(input, extensionRegistry);
        }
      };

      public static com.google.protobuf.Parser<Car> parser() {
        return PARSER;
      }

      @Override
      public com.google.protobuf.Parser<Car> getParserForType() {
        return PARSER;
      }

      @Override
      public Car getDefaultInstanceForType() {
        return DEFAULT_INSTANCE;
      }

    }

    private int bitField0_;
    public static final int ID_FIELD_NUMBER = 1;
    private int id_;
    /**
     * <code>required int32 id = 1;</code>
     */
    public boolean hasId() {
      return ((bitField0_ & 0x00000001) != 0);
    }
    /**
     * <code>required int32 id = 1;</code>
     */
    public int getId() {
      return id_;
    }

    public static final int NAME_FIELD_NUMBER = 2;
    private volatile Object name_;
    /**
     * <code>required string name = 2;</code>
     */
    public boolean hasName() {
      return ((bitField0_ & 0x00000002) != 0);
    }
    /**
     * <code>required string name = 2;</code>
     */
    public String getName() {
      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 (bs.isValidUtf8()) {
          name_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string name = 2;</code>
     */
    public com.google.protobuf.ByteString
        getNameBytes() {
      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;
      }
    }

    public static final int EMAIL_FIELD_NUMBER = 3;
    private volatile Object email_;
    /**
     * <code>optional string email = 3;</code>
     */
    public boolean hasEmail() {
      return ((bitField0_ & 0x00000004) != 0);
    }
    /**
     * <code>optional string email = 3;</code>
     */
    public String getEmail() {
      Object ref = email_;
      if (ref instanceof String) {
        return (String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          email_ = s;
        }
        return s;
      }
    }
    /**
     * <code>optional string email = 3;</code>
     */
    public com.google.protobuf.ByteString
        getEmailBytes() {
      Object ref = email_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (String) ref);
        email_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int CARS_FIELD_NUMBER = 4;
    private java.util.List<Car> cars_;
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    public java.util.List<Car> getCarsList() {
      return cars_;
    }
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    public java.util.List<? extends CarOrBuilder>
        getCarsOrBuilderList() {
      return cars_;
    }
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    public int getCarsCount() {
      return cars_.size();
    }
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    public Car getCars(int index) {
      return cars_.get(index);
    }
    /**
     * <code>repeated .RichMan.Car cars = 4;</code>
     */
    public CarOrBuilder getCarsOrBuilder(
        int index) {
      return cars_.get(index);
    }

    private byte memoizedIsInitialized = -1;
    @Override
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized == 1) return true;
      if (isInitialized == 0) return false;

      if (!hasId()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasName()) {
        memoizedIsInitialized = 0;
        return false;
      }
      for (int i = 0; i < getCarsCount(); i++) {
        if (!getCars(i).isInitialized()) {
          memoizedIsInitialized = 0;
          return false;
        }
      }
      memoizedIsInitialized = 1;
      return true;
    }

    @Override
    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      if (((bitField0_ & 0x00000001) != 0)) {
        output.writeInt32(1, id_);
      }
      if (((bitField0_ & 0x00000002) != 0)) {
        com.google.protobuf.GeneratedMessageV3.writeString(output, 2, name_);
      }
      if (((bitField0_ & 0x00000004) != 0)) {
        com.google.protobuf.GeneratedMessageV3.writeString(output, 3, email_);
      }
      for (int i = 0; i < cars_.size(); i++) {
        output.writeMessage(4, cars_.get(i));
      }
      unknownFields.writeTo(output);
    }

    @Override
    public int getSerializedSize() {
      int size = memoizedSize;
      if (size != -1) return size;

      size = 0;
      if (((bitField0_ & 0x00000001) != 0)) {
        size += com.google.protobuf.CodedOutputStream
          .computeInt32Size(1, id_);
      }
      if (((bitField0_ & 0x00000002) != 0)) {
        size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, name_);
      }
      if (((bitField0_ & 0x00000004) != 0)) {
        size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, email_);
      }
      for (int i = 0; i < cars_.size(); i++) {
        size += com.google.protobuf.CodedOutputStream
          .computeMessageSize(4, cars_.get(i));
      }
      size += unknownFields.getSerializedSize();
      memoizedSize = size;
      return size;
    }

    @Override
    public boolean equals(final Object obj) {
      if (obj == this) {
       return true;
      }
      if (!(obj instanceof RichMan)) {
        return super.equals(obj);
      }
      RichMan other = (RichMan) obj;

      if (hasId() != other.hasId()) return false;
      if (hasId()) {
        if (getId()
            != other.getId()) return false;
      }
      if (hasName() != other.hasName()) return false;
      if (hasName()) {
        if (!getName()
            .equals(other.getName())) return false;
      }
      if (hasEmail() != other.hasEmail()) return false;
      if (hasEmail()) {
        if (!getEmail()
            .equals(other.getEmail())) return false;
      }
      if (!getCarsList()
          .equals(other.getCarsList())) return false;
      if (!unknownFields.equals(other.unknownFields)) return false;
      return true;
    }

    @Override
    public int hashCode() {
      if (memoizedHashCode != 0) {
        return memoizedHashCode;
      }
      int hash = 41;
      hash = (19 * hash) + getDescriptor().hashCode();
      if (hasId()) {
        hash = (37 * hash) + ID_FIELD_NUMBER;
        hash = (53 * hash) + getId();
      }
      if (hasName()) {
        hash = (37 * hash) + NAME_FIELD_NUMBER;
        hash = (53 * hash) + getName().hashCode();
      }
      if (hasEmail()) {
        hash = (37 * hash) + EMAIL_FIELD_NUMBER;
        hash = (53 * hash) + getEmail().hashCode();
      }
      if (getCarsCount() > 0) {
        hash = (37 * hash) + CARS_FIELD_NUMBER;
        hash = (53 * hash) + getCarsList().hashCode();
      }
      hash = (29 * hash) + unknownFields.hashCode();
      memoizedHashCode = hash;
      return hash;
    }

    public static RichMan parseFrom(
        java.nio.ByteBuffer data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static RichMan parseFrom(
        java.nio.ByteBuffer data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static RichMan parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static RichMan parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static RichMan parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static RichMan parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static RichMan parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return com.google.protobuf.GeneratedMessageV3
          .parseWithIOException(PARSER, input);
    }
    public static RichMan parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return com.google.protobuf.GeneratedMessageV3
          .parseWithIOException(PARSER, input, extensionRegistry);
    }
    public static RichMan parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return com.google.protobuf.GeneratedMessageV3
          .parseDelimitedWithIOException(PARSER, input);
    }
    public static RichMan parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return com.google.protobuf.GeneratedMessageV3
          .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
    }
    public static RichMan parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return com.google.protobuf.GeneratedMessageV3
          .parseWithIOException(PARSER, input);
    }
    public static RichMan parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return com.google.protobuf.GeneratedMessageV3
          .parseWithIOException(PARSER, input, extensionRegistry);
    }

    @Override
    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder() {
      return DEFAULT_INSTANCE.toBuilder();
    }
    public static Builder newBuilder(RichMan prototype) {
      return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
    }
    @Override
    public Builder toBuilder() {
      return this == DEFAULT_INSTANCE
          ? new Builder() : new Builder().mergeFrom(this);
    }

    @Override
    protected Builder newBuilderForType(
        BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code RichMan}
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
        // @@protoc_insertion_point(builder_implements:RichMan)
        RichManOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return RichManProto.internal_static_RichMan_descriptor;
      }

      @Override
      protected FieldAccessorTable
          internalGetFieldAccessorTable() {
        return RichManProto.internal_static_RichMan_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                RichMan.class, Builder.class);
      }

      // Construct using com.ssy.netty.proto.RichManProto.RichMan.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessageV3
                .alwaysUseFieldBuilders) {
          getCarsFieldBuilder();
        }
      }
      @Override
      public Builder clear() {
        super.clear();
        id_ = 0;
        bitField0_ = (bitField0_ & ~0x00000001);
        name_ = "";
        bitField0_ = (bitField0_ & ~0x00000002);
        email_ = "";
        bitField0_ = (bitField0_ & ~0x00000004);
        if (carsBuilder_ == null) {
          cars_ = java.util.Collections.emptyList();
          bitField0_ = (bitField0_ & ~0x00000008);
        } else {
          carsBuilder_.clear();
        }
        return this;
      }

      @Override
      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return RichManProto.internal_static_RichMan_descriptor;
      }

      @Override
      public RichMan getDefaultInstanceForType() {
        return RichMan.getDefaultInstance();
      }

      @Override
      public RichMan build() {
        RichMan result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      @Override
      public RichMan buildPartial() {
        RichMan result = new RichMan(this);
        int from_bitField0_ = bitField0_;
        int to_bitField0_ = 0;
        if (((from_bitField0_ & 0x00000001) != 0)) {
          result.id_ = id_;
          to_bitField0_ |= 0x00000001;
        }
        if (((from_bitField0_ & 0x00000002) != 0)) {
          to_bitField0_ |= 0x00000002;
        }
        result.name_ = name_;
        if (((from_bitField0_ & 0x00000004) != 0)) {
          to_bitField0_ |= 0x00000004;
        }
        result.email_ = email_;
        if (carsBuilder_ == null) {
          if (((bitField0_ & 0x00000008) != 0)) {
            cars_ = java.util.Collections.unmodifiableList(cars_);
            bitField0_ = (bitField0_ & ~0x00000008);
          }
          result.cars_ = cars_;
        } else {
          result.cars_ = carsBuilder_.build();
        }
        result.bitField0_ = to_bitField0_;
        onBuilt();
        return result;
      }

      @Override
      public Builder clone() {
        return super.clone();
      }
      @Override
      public Builder setField(
          com.google.protobuf.Descriptors.FieldDescriptor field,
          Object value) {
        return super.setField(field, value);
      }
      @Override
      public Builder clearField(
          com.google.protobuf.Descriptors.FieldDescriptor field) {
        return super.clearField(field);
      }
      @Override
      public Builder clearOneof(
          com.google.protobuf.Descriptors.OneofDescriptor oneof) {
        return super.clearOneof(oneof);
      }
      @Override
      public Builder setRepeatedField(
          com.google.protobuf.Descriptors.FieldDescriptor field,
          int index, Object value) {
        return super.setRepeatedField(field, index, value);
      }
      @Override
      public Builder addRepeatedField(
          com.google.protobuf.Descriptors.FieldDescriptor field,
          Object value) {
        return super.addRepeatedField(field, value);
      }
      @Override
      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof RichMan) {
          return mergeFrom((RichMan)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(RichMan other) {
        if (other == RichMan.getDefaultInstance()) return this;
        if (other.hasId()) {
          setId(other.getId());
        }
        if (other.hasName()) {
          bitField0_ |= 0x00000002;
          name_ = other.name_;
          onChanged();
        }
        if (other.hasEmail()) {
          bitField0_ |= 0x00000004;
          email_ = other.email_;
          onChanged();
        }
        if (carsBuilder_ == null) {
          if (!other.cars_.isEmpty()) {
            if (cars_.isEmpty()) {
              cars_ = other.cars_;
              bitField0_ = (bitField0_ & ~0x00000008);
            } else {
              ensureCarsIsMutable();
              cars_.addAll(other.cars_);
            }
            onChanged();
          }
        } else {
          if (!other.cars_.isEmpty()) {
            if (carsBuilder_.isEmpty()) {
              carsBuilder_.dispose();
              carsBuilder_ = null;
              cars_ = other.cars_;
              bitField0_ = (bitField0_ & ~0x00000008);
              carsBuilder_ = 
                com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
                   getCarsFieldBuilder() : null;
            } else {
              carsBuilder_.addAllMessages(other.cars_);
            }
          }
        }
        this.mergeUnknownFields(other.unknownFields);
        onChanged();
        return this;
      }

      @Override
      public final boolean isInitialized() {
        if (!hasId()) {
          return false;
        }
        if (!hasName()) {
          return false;
        }
        for (int i = 0; i < getCarsCount(); i++) {
          if (!getCars(i).isInitialized()) {
            return false;
          }
        }
        return true;
      }

      @Override
      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        RichMan parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (RichMan) e.getUnfinishedMessage();
          throw e.unwrapIOException();
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }
      private int bitField0_;

      private int id_ ;
      /**
       * <code>required int32 id = 1;</code>
       */
      public boolean hasId() {
        return ((bitField0_ & 0x00000001) != 0);
      }
      /**
       * <code>required int32 id = 1;</code>
       */
      public int getId() {
        return id_;
      }
      /**
       * <code>required int32 id = 1;</code>
       */
      public Builder setId(int value) {
        bitField0_ |= 0x00000001;
        id_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required int32 id = 1;</code>
       */
      public Builder clearId() {
        bitField0_ = (bitField0_ & ~0x00000001);
        id_ = 0;
        onChanged();
        return this;
      }

      private Object name_ = "";
      /**
       * <code>required string name = 2;</code>
       */
      public boolean hasName() {
        return ((bitField0_ & 0x00000002) != 0);
      }
      /**
       * <code>required string name = 2;</code>
       */
      public String getName() {
        Object ref = name_;
        if (!(ref instanceof String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            name_ = s;
          }
          return s;
        } else {
          return (String) ref;
        }
      }
      /**
       * <code>required string name = 2;</code>
       */
      public com.google.protobuf.ByteString
          getNameBytes() {
        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;
        }
      }
      /**
       * <code>required string name = 2;</code>
       */
      public Builder setName(
          String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        name_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string name = 2;</code>
       */
      public Builder clearName() {
        bitField0_ = (bitField0_ & ~0x00000002);
        name_ = getDefaultInstance().getName();
        onChanged();
        return this;
      }
      /**
       * <code>required string name = 2;</code>
       */
      public Builder setNameBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        name_ = value;
        onChanged();
        return this;
      }

      private Object email_ = "";
      /**
       * <code>optional string email = 3;</code>
       */
      public boolean hasEmail() {
        return ((bitField0_ & 0x00000004) != 0);
      }
      /**
       * <code>optional string email = 3;</code>
       */
      public String getEmail() {
        Object ref = email_;
        if (!(ref instanceof String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            email_ = s;
          }
          return s;
        } else {
          return (String) ref;
        }
      }
      /**
       * <code>optional string email = 3;</code>
       */
      public com.google.protobuf.ByteString
          getEmailBytes() {
        Object ref = email_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (String) ref);
          email_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>optional string email = 3;</code>
       */
      public Builder setEmail(
          String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        email_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>optional string email = 3;</code>
       */
      public Builder clearEmail() {
        bitField0_ = (bitField0_ & ~0x00000004);
        email_ = getDefaultInstance().getEmail();
        onChanged();
        return this;
      }
      /**
       * <code>optional string email = 3;</code>
       */
      public Builder setEmailBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        email_ = value;
        onChanged();
        return this;
      }

      private java.util.List<Car> cars_ =
        java.util.Collections.emptyList();
      private void ensureCarsIsMutable() {
        if (!((bitField0_ & 0x00000008) != 0)) {
          cars_ = new java.util.ArrayList<Car>(cars_);
          bitField0_ |= 0x00000008;
         }
      }

      private com.google.protobuf.RepeatedFieldBuilderV3<
          Car, Car.Builder, CarOrBuilder> carsBuilder_;

      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public java.util.List<Car> getCarsList() {
        if (carsBuilder_ == null) {
          return java.util.Collections.unmodifiableList(cars_);
        } else {
          return carsBuilder_.getMessageList();
        }
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public int getCarsCount() {
        if (carsBuilder_ == null) {
          return cars_.size();
        } else {
          return carsBuilder_.getCount();
        }
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Car getCars(int index) {
        if (carsBuilder_ == null) {
          return cars_.get(index);
        } else {
          return carsBuilder_.getMessage(index);
        }
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder setCars(
          int index, Car value) {
        if (carsBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          ensureCarsIsMutable();
          cars_.set(index, value);
          onChanged();
        } else {
          carsBuilder_.setMessage(index, value);
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder setCars(
          int index, Car.Builder builderForValue) {
        if (carsBuilder_ == null) {
          ensureCarsIsMutable();
          cars_.set(index, builderForValue.build());
          onChanged();
        } else {
          carsBuilder_.setMessage(index, builderForValue.build());
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder addCars(Car value) {
        if (carsBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          ensureCarsIsMutable();
          cars_.add(value);
          onChanged();
        } else {
          carsBuilder_.addMessage(value);
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder addCars(
          int index, Car value) {
        if (carsBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          ensureCarsIsMutable();
          cars_.add(index, value);
          onChanged();
        } else {
          carsBuilder_.addMessage(index, value);
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder addCars(
          Car.Builder builderForValue) {
        if (carsBuilder_ == null) {
          ensureCarsIsMutable();
          cars_.add(builderForValue.build());
          onChanged();
        } else {
          carsBuilder_.addMessage(builderForValue.build());
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder addCars(
          int index, Car.Builder builderForValue) {
        if (carsBuilder_ == null) {
          ensureCarsIsMutable();
          cars_.add(index, builderForValue.build());
          onChanged();
        } else {
          carsBuilder_.addMessage(index, builderForValue.build());
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder addAllCars(
          Iterable<? extends Car> values) {
        if (carsBuilder_ == null) {
          ensureCarsIsMutable();
          com.google.protobuf.AbstractMessageLite.Builder.addAll(
              values, cars_);
          onChanged();
        } else {
          carsBuilder_.addAllMessages(values);
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder clearCars() {
        if (carsBuilder_ == null) {
          cars_ = java.util.Collections.emptyList();
          bitField0_ = (bitField0_ & ~0x00000008);
          onChanged();
        } else {
          carsBuilder_.clear();
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Builder removeCars(int index) {
        if (carsBuilder_ == null) {
          ensureCarsIsMutable();
          cars_.remove(index);
          onChanged();
        } else {
          carsBuilder_.remove(index);
        }
        return this;
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Car.Builder getCarsBuilder(
          int index) {
        return getCarsFieldBuilder().getBuilder(index);
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public CarOrBuilder getCarsOrBuilder(
          int index) {
        if (carsBuilder_ == null) {
          return cars_.get(index);  } else {
          return carsBuilder_.getMessageOrBuilder(index);
        }
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public java.util.List<? extends CarOrBuilder>
           getCarsOrBuilderList() {
        if (carsBuilder_ != null) {
          return carsBuilder_.getMessageOrBuilderList();
        } else {
          return java.util.Collections.unmodifiableList(cars_);
        }
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Car.Builder addCarsBuilder() {
        return getCarsFieldBuilder().addBuilder(
            Car.getDefaultInstance());
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public Car.Builder addCarsBuilder(
          int index) {
        return getCarsFieldBuilder().addBuilder(
            index, Car.getDefaultInstance());
      }
      /**
       * <code>repeated .RichMan.Car cars = 4;</code>
       */
      public java.util.List<Car.Builder>
           getCarsBuilderList() {
        return getCarsFieldBuilder().getBuilderList();
      }
      private com.google.protobuf.RepeatedFieldBuilderV3<
          Car, Car.Builder, CarOrBuilder>
          getCarsFieldBuilder() {
        if (carsBuilder_ == null) {
          carsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
              Car, Car.Builder, CarOrBuilder>(
                  cars_,
                  ((bitField0_ & 0x00000008) != 0),
                  getParentForChildren(),
                  isClean());
          cars_ = null;
        }
        return carsBuilder_;
      }
      @Override
      public final Builder setUnknownFields(
          final com.google.protobuf.UnknownFieldSet unknownFields) {
        return super.setUnknownFields(unknownFields);
      }

      @Override
      public final Builder mergeUnknownFields(
          final com.google.protobuf.UnknownFieldSet unknownFields) {
        return super.mergeUnknownFields(unknownFields);
      }


      // @@protoc_insertion_point(builder_scope:RichMan)
    }

    // @@protoc_insertion_point(class_scope:RichMan)
    private static final RichMan DEFAULT_INSTANCE;
    static {
      DEFAULT_INSTANCE = new RichMan();
    }

    public static RichMan getDefaultInstance() {
      return DEFAULT_INSTANCE;
    }

    @Deprecated public static final com.google.protobuf.Parser<RichMan>
        PARSER = new com.google.protobuf.AbstractParser<RichMan>() {
      @Override
      public RichMan parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return new RichMan(input, extensionRegistry);
      }
    };

    public static com.google.protobuf.Parser<RichMan> parser() {
      return PARSER;
    }

    @Override
    public com.google.protobuf.Parser<RichMan> getParserForType() {
      return PARSER;
    }

    @Override
    public RichMan getDefaultInstanceForType() {
      return DEFAULT_INSTANCE;
    }

  }

  private static final com.google.protobuf.Descriptors.Descriptor
    internal_static_RichMan_descriptor;
  private static final 
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_RichMan_fieldAccessorTable;
  private static final com.google.protobuf.Descriptors.Descriptor
    internal_static_RichMan_Car_descriptor;
  private static final 
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_RichMan_Car_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    String[] descriptorData = {
      "

RichMan.proto"30601
07RichMan22

02id3001 02(0522" +
      "14
04name3002 02(	22
05email3003 01(	2232
04cars3004 03" +
      "(13214.RichMan.Car329
03Car2214
04name3001 02(	22$
" +
      "04type3002 01(16220.RichMan.CarType:04BENZ";
07C" +
      "arType2210
04AUDI20002210
04BENZ20012217
13LAMBORGHIN" +
      "I20022213
07DASAUTO2003B#
23com.ssy.netty.protoB" +
      "14RichManProto"
    };
    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;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        }, assigner);
    internal_static_RichMan_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_RichMan_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_RichMan_descriptor,
        new String[] { "Id", "Name", "Email", "Cars", });
    internal_static_RichMan_Car_descriptor =
      internal_static_RichMan_descriptor.getNestedTypes().get(0);
    internal_static_RichMan_Car_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_RichMan_Car_descriptor,
        new String[] { "Name", "Type", });
  }

  // @@protoc_insertion_point(outer_class_scope)
}
View Code

第三步:编写Netty服务端ProtoBufServer 

package com.ssy.netty.proto;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ProtoBufServer {

    public void bind(int port) throws Exception {
        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                    ch.pipeline().addLast(new ProtobufDecoder(RichManProto.RichMan.getDefaultInstance()));
                    ch.pipeline().addLast(new ProtoBufServerHandler());
                }
            });

            // 绑定端口,同步等待成功
            ChannelFuture f = b.bind(port).sync();

            System.out.println("init start");
            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new ProtoBufServer().bind(port);
    }

}

第四步:编写 ProtoBufServerHandler

package com.ssy.netty.proto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.List;

import com.ssy.netty.proto.RichManProto.RichMan.Car;

public class ProtoBufServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RichManProto.RichMan req = (RichManProto.RichMan) msg;
        System.out.println(req.getName()+"他有"+req.getCarsCount()+"量车");
        List<Car> lists = req.getCarsList();
        if(null != lists) {

            for(Car car : lists){
                System.out.println(car.getName());
            }
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}

 第五步:编写客户端程序

package com.ssy.netty.proto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.ArrayList;
import java.util.List;

import com.ssy.netty.proto.RichManProto.RichMan.Car;
import com.ssy.netty.proto.RichManProto.RichMan.CarType;

public class ProtoBufClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("=======================================");
        RichManProto.RichMan.Builder builder = RichManProto.RichMan.newBuilder();
        builder.setName("王思聪");
        builder.setId(1);
        builder.setEmail("wsc@163.com");

        List<RichManProto.RichMan.Car> cars = new ArrayList<RichManProto.RichMan.Car>();
        Car car1 = RichManProto.RichMan.Car.newBuilder().setName("上海大众超跑").setType(CarType.DASAUTO).build();
        Car car2 = RichManProto.RichMan.Car.newBuilder().setName("Aventador").setType(CarType.LAMBORGHINI).build();
        Car car3 = RichManProto.RichMan.Car.newBuilder().setName("奔驰SLS级AMG").setType(CarType.BENZ).build();

        cars.add(car1);
        cars.add(car2);
        cars.add(car3);

        builder.addAllCars(cars);
        ctx.writeAndFlush(builder.build());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}

好了,到此为止,所有的代码已经写完毕了,我们运行测试一下:

至此,Google Protobuf与Netty的结合示例已完成,下节我们介绍Apache Thrift

原文地址:https://www.cnblogs.com/happy2010/p/10885758.html