目 录CONTENT

文章目录

Java中使用ProtoBuf数据

Carol
2023-02-02 / 0 评论 / 0 点赞 / 29 阅读 / 0 字 / 正在检测是否收录...

😋特惠💰

多个付费教程捆绑包限时特惠,8折打包购买: 详情点击爱发电 ~~~

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;
    }
}
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区