Java中使用Protobuf數據

前置要求Protobuf

安裝protobuf環境

因爲我是直接在我服務器上安裝的,下面簡單寫寫安裝步驟。
OS: Centos7.6

[root@VM_0_15_centos tools]#cd /data/tools
[root@VM_0_15_centos tools]#wget https://github.com/google/protobuf/releases/download/v3.6.1/protobuf-all-3.6.1.tar.gz
[root@VM_0_15_centos tools]#tar -zxvf protobuf-all-3.6.1.tar.gz
[root@VM_0_15_centos tools]#cd protobuf-3.6.1
[root@VM_0_15_centos protobuf-3.6.1]#yum install gcc gcc-c++
[root@VM_0_15_centos protobuf-3.6.1]#yum -y install gcc automake autoconf libtool make
[root@VM_0_15_centos protobuf-3.6.1]#./autogen.sh
[root@VM_0_15_centos protobuf-3.6.1]#./configure
[root@VM_0_15_centos protobuf-3.6.1]#make
[root@VM_0_15_centos protobuf-3.6.1]#make install

首先寫一個protobuf文件定義數據格式

syntax = "proto3";

package cnkj.site.data;

message ProtobufEntity {
    /**Header 爲必選字段
     */

    map<string,string> headers = 10;
    
    /***desc爲預留字段
     */
    reserved "desc" ;
    
    /**
        字節列表,預防傳遞非字符串類型數據
     */
     bytes body  = 2;
}

根據上面的protobuf文件生成一個java文件

java文件由pb自動生成,使用的時候直接拷貝到自己的項目裏面即可

[root@VM_0_15_centos tools]# ./protobuf-3.6.1/src/protoc -I=./ --java_out=./ ./ProtobufOuter.proto
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: ProtobufOuter.proto

package cnkj.site.data;

public final class ProtobufOuter {
    private ProtobufOuter() {}
    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 ProtobufEntityOrBuilder extends
            // @@protoc_insertion_point(interface_extends:cnkj.site.data.ProtobufEntity)
            com.google.protobuf.MessageOrBuilder {

        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */
        int getHeadersCount();
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */
        boolean containsHeaders(
                java.lang.String key);
        /**
         * Use {@link #getHeadersMap()} instead.
         */
        @java.lang.Deprecated
        java.util.Map<java.lang.String, java.lang.String>
        getHeaders();
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */
        java.util.Map<java.lang.String, java.lang.String>
        getHeadersMap();
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */

        java.lang.String getHeadersOrDefault(
                java.lang.String key,
                java.lang.String defaultValue);
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */

        java.lang.String getHeadersOrThrow(
                java.lang.String key);

        /**
         * <pre>
         **
         *字節列表,預防傳遞非字符串類型數據
         * </pre>
         *
         * <code>bytes body = 2;</code>
         */
        com.google.protobuf.ByteString getBody();
    }
    /**
     * <pre>
     **Header 爲必選字段
     * </pre>
     *
     * Protobuf type {@code cnkj.site.data.ProtobufEntity}
     */
    public  static final class ProtobufEntity extends
            com.google.protobuf.GeneratedMessageV3 implements
            // @@protoc_insertion_point(message_implements:cnkj.site.data.ProtobufEntity)
            ProtobufEntityOrBuilder {
        private static final long serialVersionUID = 0L;
        // Use ProtobufEntity.newBuilder() to construct.
        private ProtobufEntity(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
            super(builder);
        }
        private ProtobufEntity() {
            body_ = com.google.protobuf.ByteString.EMPTY;
        }

        @java.lang.Override
        public final com.google.protobuf.UnknownFieldSet
        getUnknownFields() {
            return this.unknownFields;
        }
        private ProtobufEntity(
                com.google.protobuf.CodedInputStream input,
                com.google.protobuf.ExtensionRegistryLite extensionRegistry)
                throws com.google.protobuf.InvalidProtocolBufferException {
            this();
            if (extensionRegistry == null) {
                throw new java.lang.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 18: {

                            body_ = input.readBytes();
                            break;
                        }
                        case 82: {
                            if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
                                headers_ = com.google.protobuf.MapField.newMapField(
                                        HeadersDefaultEntryHolder.defaultEntry);
                                mutable_bitField0_ |= 0x00000001;
                            }
                            com.google.protobuf.MapEntry<java.lang.String, java.lang.String>
                                    headers__ = input.readMessage(
                                    HeadersDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry);
                            headers_.getMutableMap().put(
                                    headers__.getKey(), headers__.getValue());
                            break;
                        }
                        default: {
                            if (!parseUnknownFieldProto3(
                                    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 cnkj.site.data.ProtobufOuter.internal_static_cnkj_site_data_ProtobufEntity_descriptor;
        }

        @SuppressWarnings({"rawtypes"})
        @java.lang.Override
        protected com.google.protobuf.MapField internalGetMapField(
                int number) {
            switch (number) {
                case 10:
                    return internalGetHeaders();
                default:
                    throw new RuntimeException(
                            "Invalid map field number: " + number);
            }
        }
        @java.lang.Override
        protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
            return cnkj.site.data.ProtobufOuter.internal_static_cnkj_site_data_ProtobufEntity_fieldAccessorTable
                    .ensureFieldAccessorsInitialized(
                            cnkj.site.data.ProtobufOuter.ProtobufEntity.class, cnkj.site.data.ProtobufOuter.ProtobufEntity.Builder.class);
        }

        private int bitField0_;
        public static final int HEADERS_FIELD_NUMBER = 10;
        private static final class HeadersDefaultEntryHolder {
            static final com.google.protobuf.MapEntry<
                    java.lang.String, java.lang.String> defaultEntry =
                    com.google.protobuf.MapEntry
                            .<java.lang.String, java.lang.String>newDefaultInstance(
                                    cnkj.site.data.ProtobufOuter.internal_static_cnkj_site_data_ProtobufEntity_HeadersEntry_descriptor,
                                    com.google.protobuf.WireFormat.FieldType.STRING,
                                    "",
                                    com.google.protobuf.WireFormat.FieldType.STRING,
                                    "");
        }
        private com.google.protobuf.MapField<
                java.lang.String, java.lang.String> headers_;
        private com.google.protobuf.MapField<java.lang.String, java.lang.String>
        internalGetHeaders() {
            if (headers_ == null) {
                return com.google.protobuf.MapField.emptyMapField(
                        HeadersDefaultEntryHolder.defaultEntry);
            }
            return headers_;
        }

        public int getHeadersCount() {
            return internalGetHeaders().getMap().size();
        }
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */

        public boolean containsHeaders(
                java.lang.String key) {
            if (key == null) { throw new java.lang.NullPointerException(); }
            return internalGetHeaders().getMap().containsKey(key);
        }
        /**
         * Use {@link #getHeadersMap()} instead.
         */
        @java.lang.Deprecated
        public java.util.Map<java.lang.String, java.lang.String> getHeaders() {
            return getHeadersMap();
        }
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */

        public java.util.Map<java.lang.String, java.lang.String> getHeadersMap() {
            return internalGetHeaders().getMap();
        }
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */

        public java.lang.String getHeadersOrDefault(
                java.lang.String key,
                java.lang.String defaultValue) {
            if (key == null) { throw new java.lang.NullPointerException(); }
            java.util.Map<java.lang.String, java.lang.String> map =
                    internalGetHeaders().getMap();
            return map.containsKey(key) ? map.get(key) : defaultValue;
        }
        /**
         * <code>map&lt;string, string&gt; headers = 10;</code>
         */

        public java.lang.String getHeadersOrThrow(
                java.lang.String key) {
            if (key == null) { throw new java.lang.NullPointerException(); }
            java.util.Map<java.lang.String, java.lang.String> map =
                    internalGetHeaders().getMap();
            if (!map.containsKey(key)) {
                throw new java.lang.IllegalArgumentException();
            }
            return map.get(key);
        }

        public static final int BODY_FIELD_NUMBER = 2;
        private com.google.protobuf.ByteString body_;
        /**
         * <pre>
         **
         *字節列表,預防傳遞非字符串類型數據
         * </pre>
         *
         * <code>bytes body = 2;</code>
         */
        public com.google.protobuf.ByteString getBody() {
            return body_;
        }

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

            memoizedIsInitialized = 1;
            return true;
        }

        @java.lang.Override
        public void writeTo(com.google.protobuf.CodedOutputStream output)
                throws java.io.IOException {
            if (!body_.isEmpty()) {
                output.writeBytes(2, body_);
            }
            com.google.protobuf.GeneratedMessageV3
                    .serializeStringMapTo(
                            output,
                            internalGetHeaders(),
                            HeadersDefaultEntryHolder.defaultEntry,
                            10);
            unknownFields.writeTo(output);
        }

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

            size = 0;
            if (!body_.isEmpty()) {
                size += com.google.protobuf.CodedOutputStream
                        .computeBytesSize(2, body_);
            }
            for (java.util.Map.Entry<java.lang.String, java.lang.String> entry
                    : internalGetHeaders().getMap().entrySet()) {
                com.google.protobuf.MapEntry<java.lang.String, java.lang.String>
                        headers__ = HeadersDefaultEntryHolder.defaultEntry.newBuilderForType()
                        .setKey(entry.getKey())
                        .setValue(entry.getValue())
                        .build();
                size += com.google.protobuf.CodedOutputStream
                        .computeMessageSize(10, headers__);
            }
            size += unknownFields.getSerializedSize();
            memoizedSize = size;
            return size;
        }

        @java.lang.Override
        public boolean equals(final java.lang.Object obj) {
            if (obj == this) {
                return true;
            }
            if (!(obj instanceof cnkj.site.data.ProtobufOuter.ProtobufEntity)) {
                return super.equals(obj);
            }
            cnkj.site.data.ProtobufOuter.ProtobufEntity other = (cnkj.site.data.ProtobufOuter.ProtobufEntity) obj;

            boolean result = true;
            result = result && internalGetHeaders().equals(
                    other.internalGetHeaders());
            result = result && getBody()
                    .equals(other.getBody());
            result = result && unknownFields.equals(other.unknownFields);
            return result;
        }

        @java.lang.Override
        public int hashCode() {
            if (memoizedHashCode != 0) {
                return memoizedHashCode;
            }
            int hash = 41;
            hash = (19 * hash) + getDescriptor().hashCode();
            if (!internalGetHeaders().getMap().isEmpty()) {
                hash = (37 * hash) + HEADERS_FIELD_NUMBER;
                hash = (53 * hash) + internalGetHeaders().hashCode();
            }
            hash = (37 * hash) + BODY_FIELD_NUMBER;
            hash = (53 * hash) + getBody().hashCode();
            hash = (29 * hash) + unknownFields.hashCode();
            memoizedHashCode = hash;
            return hash;
        }

        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(
                java.nio.ByteBuffer data)
                throws com.google.protobuf.InvalidProtocolBufferException {
            return PARSER.parseFrom(data);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(
                java.nio.ByteBuffer data,
                com.google.protobuf.ExtensionRegistryLite extensionRegistry)
                throws com.google.protobuf.InvalidProtocolBufferException {
            return PARSER.parseFrom(data, extensionRegistry);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(
                com.google.protobuf.ByteString data)
                throws com.google.protobuf.InvalidProtocolBufferException {
            return PARSER.parseFrom(data);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(
                com.google.protobuf.ByteString data,
                com.google.protobuf.ExtensionRegistryLite extensionRegistry)
                throws com.google.protobuf.InvalidProtocolBufferException {
            return PARSER.parseFrom(data, extensionRegistry);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(byte[] data)
                throws com.google.protobuf.InvalidProtocolBufferException {
            return PARSER.parseFrom(data);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(
                byte[] data,
                com.google.protobuf.ExtensionRegistryLite extensionRegistry)
                throws com.google.protobuf.InvalidProtocolBufferException {
            return PARSER.parseFrom(data, extensionRegistry);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(java.io.InputStream input)
                throws java.io.IOException {
            return com.google.protobuf.GeneratedMessageV3
                    .parseWithIOException(PARSER, input);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity 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 cnkj.site.data.ProtobufOuter.ProtobufEntity parseDelimitedFrom(java.io.InputStream input)
                throws java.io.IOException {
            return com.google.protobuf.GeneratedMessageV3
                    .parseDelimitedWithIOException(PARSER, input);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity 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 cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(
                com.google.protobuf.CodedInputStream input)
                throws java.io.IOException {
            return com.google.protobuf.GeneratedMessageV3
                    .parseWithIOException(PARSER, input);
        }
        public static cnkj.site.data.ProtobufOuter.ProtobufEntity parseFrom(
                com.google.protobuf.CodedInputStream input,
                com.google.protobuf.ExtensionRegistryLite extensionRegistry)
                throws java.io.IOException {
            return com.google.protobuf.GeneratedMessageV3
                    .parseWithIOException(PARSER, input, extensionRegistry);
        }

        @java.lang.Override
        public Builder newBuilderForType() { return newBuilder(); }
        public static Builder newBuilder() {
            return DEFAULT_INSTANCE.toBuilder();
        }
        public static Builder newBuilder(cnkj.site.data.ProtobufOuter.ProtobufEntity prototype) {
            return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
        }
        @java.lang.Override
        public Builder toBuilder() {
            return this == DEFAULT_INSTANCE
                    ? new Builder() : new Builder().mergeFrom(this);
        }

        @java.lang.Override
        protected Builder newBuilderForType(
                com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
            Builder builder = new Builder(parent);
            return builder;
        }
        /**
         * <pre>
         **Header 爲必選字段
         * </pre>
         *
         * Protobuf type {@code cnkj.site.data.ProtobufEntity}
         */
        public static final class Builder extends
                com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
                // @@protoc_insertion_point(builder_implements:cnkj.site.data.ProtobufEntity)
                cnkj.site.data.ProtobufOuter.ProtobufEntityOrBuilder {
            public static final com.google.protobuf.Descriptors.Descriptor
            getDescriptor() {
                return cnkj.site.data.ProtobufOuter.internal_static_cnkj_site_data_ProtobufEntity_descriptor;
            }

            @SuppressWarnings({"rawtypes"})
            protected com.google.protobuf.MapField internalGetMapField(
                    int number) {
                switch (number) {
                    case 10:
                        return internalGetHeaders();
                    default:
                        throw new RuntimeException(
                                "Invalid map field number: " + number);
                }
            }
            @SuppressWarnings({"rawtypes"})
            protected com.google.protobuf.MapField internalGetMutableMapField(
                    int number) {
                switch (number) {
                    case 10:
                        return internalGetMutableHeaders();
                    default:
                        throw new RuntimeException(
                                "Invalid map field number: " + number);
                }
            }
            @java.lang.Override
            protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
            internalGetFieldAccessorTable() {
                return cnkj.site.data.ProtobufOuter.internal_static_cnkj_site_data_ProtobufEntity_fieldAccessorTable
                        .ensureFieldAccessorsInitialized(
                                cnkj.site.data.ProtobufOuter.ProtobufEntity.class, cnkj.site.data.ProtobufOuter.ProtobufEntity.Builder.class);
            }

            // Construct using cnkj.site.data.ProtobufOuter.ProtobufEntity.newBuilder()
            private Builder() {
                maybeForceBuilderInitialization();
            }

            private Builder(
                    com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
                super(parent);
                maybeForceBuilderInitialization();
            }
            private void maybeForceBuilderInitialization() {
                if (com.google.protobuf.GeneratedMessageV3
                        .alwaysUseFieldBuilders) {
                }
            }
            @java.lang.Override
            public Builder clear() {
                super.clear();
                internalGetMutableHeaders().clear();
                body_ = com.google.protobuf.ByteString.EMPTY;

                return this;
            }

            @java.lang.Override
            public com.google.protobuf.Descriptors.Descriptor
            getDescriptorForType() {
                return cnkj.site.data.ProtobufOuter.internal_static_cnkj_site_data_ProtobufEntity_descriptor;
            }

            @java.lang.Override
            public cnkj.site.data.ProtobufOuter.ProtobufEntity getDefaultInstanceForType() {
                return cnkj.site.data.ProtobufOuter.ProtobufEntity.getDefaultInstance();
            }

            @java.lang.Override
            public cnkj.site.data.ProtobufOuter.ProtobufEntity build() {
                cnkj.site.data.ProtobufOuter.ProtobufEntity result = buildPartial();
                if (!result.isInitialized()) {
                    throw newUninitializedMessageException(result);
                }
                return result;
            }

            @java.lang.Override
            public cnkj.site.data.ProtobufOuter.ProtobufEntity buildPartial() {
                cnkj.site.data.ProtobufOuter.ProtobufEntity result = new cnkj.site.data.ProtobufOuter.ProtobufEntity(this);
                int from_bitField0_ = bitField0_;
                int to_bitField0_ = 0;
                result.headers_ = internalGetHeaders();
                result.headers_.makeImmutable();
                result.body_ = body_;
                result.bitField0_ = to_bitField0_;
                onBuilt();
                return result;
            }

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

            public Builder mergeFrom(cnkj.site.data.ProtobufOuter.ProtobufEntity other) {
                if (other == cnkj.site.data.ProtobufOuter.ProtobufEntity.getDefaultInstance()) return this;
                internalGetMutableHeaders().mergeFrom(
                        other.internalGetHeaders());
                if (other.getBody() != com.google.protobuf.ByteString.EMPTY) {
                    setBody(other.getBody());
                }
                this.mergeUnknownFields(other.unknownFields);
                onChanged();
                return this;
            }

            @java.lang.Override
            public final boolean isInitialized() {
                return true;
            }

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

            private com.google.protobuf.MapField<
                    java.lang.String, java.lang.String> headers_;
            private com.google.protobuf.MapField<java.lang.String, java.lang.String>
            internalGetHeaders() {
                if (headers_ == null) {
                    return com.google.protobuf.MapField.emptyMapField(
                            HeadersDefaultEntryHolder.defaultEntry);
                }
                return headers_;
            }
            private com.google.protobuf.MapField<java.lang.String, java.lang.String>
            internalGetMutableHeaders() {
                onChanged();;
                if (headers_ == null) {
                    headers_ = com.google.protobuf.MapField.newMapField(
                            HeadersDefaultEntryHolder.defaultEntry);
                }
                if (!headers_.isMutable()) {
                    headers_ = headers_.copy();
                }
                return headers_;
            }

            public int getHeadersCount() {
                return internalGetHeaders().getMap().size();
            }
            /**
             * <code>map&lt;string, string&gt; headers = 10;</code>
             */

            public boolean containsHeaders(
                    java.lang.String key) {
                if (key == null) { throw new java.lang.NullPointerException(); }
                return internalGetHeaders().getMap().containsKey(key);
            }
            /**
             * Use {@link #getHeadersMap()} instead.
             */
            @java.lang.Deprecated
            public java.util.Map<java.lang.String, java.lang.String> getHeaders() {
                return getHeadersMap();
            }
            /**
             * <code>map&lt;string, string&gt; headers = 10;</code>
             */

            public java.util.Map<java.lang.String, java.lang.String> getHeadersMap() {
                return internalGetHeaders().getMap();
            }
            /**
             * <code>map&lt;string, string&gt; headers = 10;</code>
             */

            public java.lang.String getHeadersOrDefault(
                    java.lang.String key,
                    java.lang.String defaultValue) {
                if (key == null) { throw new java.lang.NullPointerException(); }
                java.util.Map<java.lang.String, java.lang.String> map =
                        internalGetHeaders().getMap();
                return map.containsKey(key) ? map.get(key) : defaultValue;
            }
            /**
             * <code>map&lt;string, string&gt; headers = 10;</code>
             */

            public java.lang.String getHeadersOrThrow(
                    java.lang.String key) {
                if (key == null) { throw new java.lang.NullPointerException(); }
                java.util.Map<java.lang.String, java.lang.String> map =
                        internalGetHeaders().getMap();
                if (!map.containsKey(key)) {
                    throw new java.lang.IllegalArgumentException();
                }
                return map.get(key);
            }

            public Builder clearHeaders() {
                internalGetMutableHeaders().getMutableMap()
                        .clear();
                return this;
            }
            /**
             * <code>map&lt;string, string&gt; headers = 10;</code>
             */

            public Builder removeHeaders(
                    java.lang.String key) {
                if (key == null) { throw new java.lang.NullPointerException(); }
                internalGetMutableHeaders().getMutableMap()
                        .remove(key);
                return this;
            }
            /**
             * Use alternate mutation accessors instead.
             */
            @java.lang.Deprecated
            public java.util.Map<java.lang.String, java.lang.String>
            getMutableHeaders() {
                return internalGetMutableHeaders().getMutableMap();
            }
            /**
             * <code>map&lt;string, string&gt; headers = 10;</code>
             */
            public Builder putHeaders(
                    java.lang.String key,
                    java.lang.String value) {
                if (key == null) { throw new java.lang.NullPointerException(); }
                if (value == null) { throw new java.lang.NullPointerException(); }
                internalGetMutableHeaders().getMutableMap()
                        .put(key, value);
                return this;
            }
            /**
             * <code>map&lt;string, string&gt; headers = 10;</code>
             */

            public Builder putAllHeaders(
                    java.util.Map<java.lang.String, java.lang.String> values) {
                internalGetMutableHeaders().getMutableMap()
                        .putAll(values);
                return this;
            }

            private com.google.protobuf.ByteString body_ = com.google.protobuf.ByteString.EMPTY;
            /**
             * <pre>
             **
             *字節列表,預防傳遞非字符串類型數據
             * </pre>
             *
             * <code>bytes body = 2;</code>
             */
            public com.google.protobuf.ByteString getBody() {
                return body_;
            }
            /**
             * <pre>
             **
             *字節列表,預防傳遞非字符串類型數據
             * </pre>
             *
             * <code>bytes body = 2;</code>
             */
            public Builder setBody(com.google.protobuf.ByteString value) {
                if (value == null) {
                    throw new NullPointerException();
                }

                body_ = value;
                onChanged();
                return this;
            }
            /**
             * <pre>
             **
             *字節列表,預防傳遞非字符串類型數據
             * </pre>
             *
             * <code>bytes body = 2;</code>
             */
            public Builder clearBody() {

                body_ = getDefaultInstance().getBody();
                onChanged();
                return this;
            }
            @java.lang.Override
            public final Builder setUnknownFields(
                    final com.google.protobuf.UnknownFieldSet unknownFields) {
                return super.setUnknownFieldsProto3(unknownFields);
            }

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


            // @@protoc_insertion_point(builder_scope:cnkj.site.data.ProtobufEntity)
        }

        // @@protoc_insertion_point(class_scope:cnkj.site.data.ProtobufEntity)
        private static final cnkj.site.data.ProtobufOuter.ProtobufEntity DEFAULT_INSTANCE;
        static {
            DEFAULT_INSTANCE = new cnkj.site.data.ProtobufOuter.ProtobufEntity();
        }

        public static cnkj.site.data.ProtobufOuter.ProtobufEntity getDefaultInstance() {
            return DEFAULT_INSTANCE;
        }

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

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

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

        @java.lang.Override
        public cnkj.site.data.ProtobufOuter.ProtobufEntity getDefaultInstanceForType() {
            return DEFAULT_INSTANCE;
        }

    }

    private static final com.google.protobuf.Descriptors.Descriptor
            internal_static_cnkj_site_data_ProtobufEntity_descriptor;
    private static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
            internal_static_cnkj_site_data_ProtobufEntity_fieldAccessorTable;
    private static final com.google.protobuf.Descriptors.Descriptor
            internal_static_cnkj_site_data_ProtobufEntity_HeadersEntry_descriptor;
    private static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
            internal_static_cnkj_site_data_ProtobufEntity_HeadersEntry_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\nProtobufOuter.proto\022\016cnkj.site.data\"\222\001\n\016Protobu" +
                        "fEntity\022<\n\007headers\030\n \003(\0132+.cnkj.site.dat" +
                        "a.ProtobufEntity.HeadersEntry\022\014\n\004body\030\002 " +
                        "\001(\014\032.\n\014HeadersEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005valu" +
                        "e\030\002 \001(\t:\0028\001R\004descb\006proto3"
        };
        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_cnkj_site_data_ProtobufEntity_descriptor =
                getDescriptor().getMessageTypes().get(0);
        internal_static_cnkj_site_data_ProtobufEntity_fieldAccessorTable = new
                com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
                internal_static_cnkj_site_data_ProtobufEntity_descriptor,
                new java.lang.String[] { "Headers", "Body", });
        internal_static_cnkj_site_data_ProtobufEntity_HeadersEntry_descriptor =
                internal_static_cnkj_site_data_ProtobufEntity_descriptor.getNestedTypes().get(0);
        internal_static_cnkj_site_data_ProtobufEntity_HeadersEntry_fieldAccessorTable = new
                com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
                internal_static_cnkj_site_data_ProtobufEntity_HeadersEntry_descriptor,
                new java.lang.String[] { "Key", "Value", });
    }

    // @@protoc_insertion_point(outer_class_scope)
}

Maven

<dependencies>
    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java</artifactId>
        <version>3.6.1</version>
    </dependency>
    <dependency>
        <groupId>com.googlecode.protobuf-java-format</groupId>
        <artifactId>protobuf-java-format</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

操作Protobuf數據

因爲pb數據都是unmodifiable不可變的,所以我們需要進行一定的轉換才能修改原來的數據。
下面只對header部分進行操作

package cnkj.site.data;

import com.google.protobuf.ByteString;
import com.googlecode.protobuf.format.JsonFormat;

import java.util.HashMap;
import java.util.Map;

/*
 * @author  LXW
 * @create  2019/12/27 11:04
 * @Description
 *          1. body 是.proto文件中設置的對象屬性,因爲設置的是字節格式,所以這裏所有對body對象數據的操作都應當爲字節格式
 *          2. headers 是.proto文件中設置的對象屬性,因爲是map格式,所以這裏面對headers對象的操作應當全部爲map格式
 *          3. 並且因爲pb數據的特性,map對象是不可變的,因爲當使用getMap.put()方法的時候會全部拋異常
 */
public class ProtobufOuterOperation {

    /**
     * 生成pb數據
     * @param body 主題
     * @param headers 頭
     * @return pb數據的字節數組
     */
    private byte[] create(byte[] body, Map headers){
        try {
            ProtobufOuter.ProtobufEntity.Builder protobufEntity = ProtobufOuter.ProtobufEntity.newBuilder();
            protobufEntity.setBody(ByteString.copyFrom(body));
            protobufEntity.putAllHeaders(headers);
            return protobufEntity.build().toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 獲取pb數據
     * @param pb pb數據字節數組
     * @return json字符串
     */
    private String get(byte[] pb){
        try {
            ProtobufOuter.ProtobufEntity protobufEntity = ProtobufOuter.ProtobufEntity.parseFrom(pb);
            //獲取指定body內容
            ByteString body = protobufEntity.getBody();
            //獲取指定headers內容
            Map<String, String> headersMap = protobufEntity.getHeadersMap();
            //字節轉換pb數據對象爲jsonString
            String string = JsonFormat.printToString(protobufEntity);
            return string;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 編輯headers,因爲pb數據特性,獲取到的map對象是不可變的,所以我們只能重新new一個對象然後把數據放進去
     *  - 當新的map對象的屬性與原來的屬性有重複,則會覆蓋原來的數據
     *  - 否則效果等於新增
     * - 新增body同理
     * @param pb 獲取到的pb數據
     * @param headers 需要新增的headers對象
     * @return 完成新增headers後的pb數據字節
     */
    private byte[] editHeaders(byte[] pb, Map headers){
        ProtobufOuter.ProtobufEntity.Builder builder = ProtobufOuter.ProtobufEntity.newBuilder();
        try {
            ProtobufOuter.ProtobufEntity protobufEntity = ProtobufOuter.ProtobufEntity.parseFrom(pb);
            builder.setBody(protobufEntity.getBody());
            Map map = new HashMap();
            map.putAll(protobufEntity.getHeadersMap());
            map.putAll(headers);
            builder.putAllHeaders(map);
            return builder.build().toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章