gRPC编码初探(java)

背景:gRPC是一个高性能、通用的开源RPC框架,其由Google主要面向移动应用开发并基于HTTP/2协议标准而设计,基于ProtoBuf(Protocol Buffers)序列化协议开发,且支持众多开发语言。gRPC提供了一种简单的方法来精确地定义服务和为iOS、Android和后台支持服务自动生成可靠性很强的客户端功能库。客户端充分利用高级流和链接功能,从而有助于节省带宽、降低的TCP链接次数、节省CPU使用、和电池寿命。 以下初探编码过程:

1、安装插件Protobuf-dt最新版本,我的版本为2.2.1

2、下载protobuf

    找到对应操作系统版本(我的系统为OS)直接解压到某个目录(我的目录为:/Users/peng/protoc-3.0.0-beta-2-osx-x86_64),链接:https://github.com/google/protobuf

 3、新建maven项目,过程省略

 4、在pom.xml文件中添加gRPC的相关依赖  

<dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-all</artifactId>
      <version>0.13.2</version>
 </dependency>

    添加maven-protobuf-plugin,在pom.xml中添加以下内容

<build> 

    <extensions> 

        <extension> 

            <groupId>kr.motd.maven</groupId> 

            <artifactId>os-maven-plugin</artifactId> 

            <version>1.4.1.Final</version> 

        </extension> 

    </extensions> 

    <plugins> 

        <plugin> 

            <groupId>org.xolstice.maven.plugins</groupId> 

            <artifactId>protobuf-maven-plugin</artifactId> 

            <version>0.5.0</version> 

            <configuration> 

                <!-- 

                  The version of protoc must match protobuf-java. If you don't depend on 

                  protobuf-java directly, you will be transitively depending on the 

                  protobuf-java version that grpc depends on. 

                --> 

                <protocArtifact>com.google.protobuf:protoc:3.0.0-beta-2:exe:${os.detected.classifier}</protocArtifact> 

                <pluginId>grpc-java</pluginId> 

                <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.13.2:exe:${os.detected.classifier}</pluginArtifact> 

                <protocExecutable>/Users/peng/protoc-3.0.0-beta-2-osx-x86_64/protoc</protocExecutable>

            </configuration> 

            <executions> 

                <execution> 

                    <goals> 

                        <goal>compile</goal> 

                        <goal>compile-custom</goal> 

                    </goals> 

                </execution> 

            </executions> 

        </plugin> 

    </plugins> 

</build> 

注意protocExecutable节点后的目录为第2步中protobuf的安装路径

最终的pom.xml文件如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mzsg.demo</groupId>
  <artifactId>grpc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>grpc</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-all</artifactId>
      <version>0.13.2</version>
    </dependency>
  </dependencies>
  
  <build> 
        <extensions> 
            <extension> 
                <groupId>kr.motd.maven</groupId> 
                <artifactId>os-maven-plugin</artifactId> 
                <version>1.4.1.Final</version> 
            </extension> 
        </extensions> 
        <plugins> 
            <plugin> 
                <groupId>org.xolstice.maven.plugins</groupId> 
                <artifactId>protobuf-maven-plugin</artifactId> 
                <version>0.5.0</version> 
                <configuration> 
                    <!-- 
                      The version of protoc must match protobuf-java. If you don't depend on 
                      protobuf-java directly, you will be transitively depending on the 
                      protobuf-java version that grpc depends on. 
                    --> 
                    <protocArtifact>com.google.protobuf:protoc:3.0.0-beta-2:exe:${os.detected.classifier}</protocArtifact> 
                    <pluginId>grpc-java</pluginId> 
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.13.2:exe:${os.detected.classifier}</pluginArtifact> 
                    <protocExecutable>/Users/peng/protoc-3.0.0-beta-2-osx-x86_64/protoc</protocExecutable>
                </configuration> 
                <executions> 
                    <execution> 
                        <goals> 
                            <goal>compile</goal> 
                            <goal>compile-custom</goal> 
                        </goals> 
                    </execution> 
                </executions> 
            </plugin> 
        </plugins> 
    </build> 
</project>
View Code

5、编写proto文件,描述入参、出参及远程方法

在src/main下面建立proto目录,protobuf-maven-plugin默认会扫描该目录以生成java文件

在proto目录下新建文件,AccountQry.proto,内容为

syntax = "proto3";
package accountService;
option java_package = "com.mzsg.demo.grpc.qryaccount";
option java_outer_classname = "QryAccountProto";

//账户查询请求
message AccountQryRequest {
  //请求流水
  string requestId = 1;
  //用户ID
  string userId = 2;
}

//账户查询响应
message AccountQryResponse {
  //请求流水
  string requestId = 1;
  //返回码,1:成功; -1:失败
  int32 rc = 2;
  //错误消息
  string msg = 3;
  //账户余额
  int32 amount = 4;
}

/**
 * 账户操查询服务
 */
service QryAccountService {

  //账户查询方法
  rpc Qry(AccountQryRequest) returns (AccountQryResponse);
}

注意:本例用查账户查询作为demo,因为涉及到后面的性能(包括了序列化,反序列化)对比,故不再简单采用Hello world来测试

6、运行maven-generate-source,生成proto对应的java文件

生成文件结构生成文件结构
 

grpc-java下的为方法,java下的为入参出参,将这两个文件copy到com.mzsg.demo.grpc.qryaccount包下

注意:QryAccountServiceGrpc.java文件会提示@Override注解报错,直接删除注解即可,另外生成的代码也不是很简洁,有点无语

QryAccountServiceGrpc.java内容

package com.mzsg.demo.grpc.qryaccount;

import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;

@javax.annotation.Generated("by gRPC proto compiler")
public class QryAccountServiceGrpc {

  private QryAccountServiceGrpc() {}

  public static final String SERVICE_NAME = "accountService.QryAccountService";

  // Static method descriptors that strictly reflect the proto.
  @io.grpc.ExperimentalApi
  public static final io.grpc.MethodDescriptor<com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest,
      com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse> METHOD_QRY =
      io.grpc.MethodDescriptor.create(
          io.grpc.MethodDescriptor.MethodType.UNARY,
          generateFullMethodName(
              "accountService.QryAccountService", "Qry"),
          io.grpc.protobuf.ProtoUtils.marshaller(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.getDefaultInstance()),
          io.grpc.protobuf.ProtoUtils.marshaller(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.getDefaultInstance()));

  public static QryAccountServiceStub newStub(io.grpc.Channel channel) {
    return new QryAccountServiceStub(channel);
  }

  public static QryAccountServiceBlockingStub newBlockingStub(
      io.grpc.Channel channel) {
    return new QryAccountServiceBlockingStub(channel);
  }

  public static QryAccountServiceFutureStub newFutureStub(
      io.grpc.Channel channel) {
    return new QryAccountServiceFutureStub(channel);
  }

  public static interface QryAccountService {

    public void qry(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest request,
        io.grpc.stub.StreamObserver<com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse> responseObserver);
  }

  public static interface QryAccountServiceBlockingClient {

    public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse qry(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest request);
  }

  public static interface QryAccountServiceFutureClient {

    public com.google.common.util.concurrent.ListenableFuture<com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse> qry(
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest request);
  }

  public static class QryAccountServiceStub extends io.grpc.stub.AbstractStub<QryAccountServiceStub>
      implements QryAccountService {
    private QryAccountServiceStub(io.grpc.Channel channel) {
      super(channel);
    }

    private QryAccountServiceStub(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      super(channel, callOptions);
    }

    @java.lang.Override
    protected QryAccountServiceStub build(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      return new QryAccountServiceStub(channel, callOptions);
    }

    public void qry(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest request,
        io.grpc.stub.StreamObserver<com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse> responseObserver) {
      asyncUnaryCall(
          getChannel().newCall(METHOD_QRY, getCallOptions()), request, responseObserver);
    }
  }

  public static class QryAccountServiceBlockingStub extends io.grpc.stub.AbstractStub<QryAccountServiceBlockingStub>
      implements QryAccountServiceBlockingClient {
    private QryAccountServiceBlockingStub(io.grpc.Channel channel) {
      super(channel);
    }

    private QryAccountServiceBlockingStub(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      super(channel, callOptions);
    }

    @java.lang.Override
    protected QryAccountServiceBlockingStub build(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      return new QryAccountServiceBlockingStub(channel, callOptions);
    }

    public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse qry(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest request) {
      return blockingUnaryCall(
          getChannel(), METHOD_QRY, getCallOptions(), request);
    }
  }

  public static class QryAccountServiceFutureStub extends io.grpc.stub.AbstractStub<QryAccountServiceFutureStub>
      implements QryAccountServiceFutureClient {
    private QryAccountServiceFutureStub(io.grpc.Channel channel) {
      super(channel);
    }

    private QryAccountServiceFutureStub(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      super(channel, callOptions);
    }

    @java.lang.Override
    protected QryAccountServiceFutureStub build(io.grpc.Channel channel,
        io.grpc.CallOptions callOptions) {
      return new QryAccountServiceFutureStub(channel, callOptions);
    }

    public com.google.common.util.concurrent.ListenableFuture<com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse> qry(
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest request) {
      return futureUnaryCall(
          getChannel().newCall(METHOD_QRY, getCallOptions()), request);
    }
  }

  private static final int METHODID_QRY = 0;

  private static class MethodHandlers<Req, Resp> implements
      io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
      io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
      io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
      io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
    private final QryAccountService serviceImpl;
    private final int methodId;

    public MethodHandlers(QryAccountService serviceImpl, int methodId) {
      this.serviceImpl = serviceImpl;
      this.methodId = methodId;
    }

    @java.lang.SuppressWarnings("unchecked")
    public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
      switch (methodId) {
        case METHODID_QRY:
          serviceImpl.qry((com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest) request,
              (io.grpc.stub.StreamObserver<com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse>) responseObserver);
          break;
        default:
          throw new AssertionError();
      }
    }

    @java.lang.SuppressWarnings("unchecked")
    public io.grpc.stub.StreamObserver<Req> invoke(
        io.grpc.stub.StreamObserver<Resp> responseObserver) {
      switch (methodId) {
        default:
          throw new AssertionError();
      }
    }
  }

  public static io.grpc.ServerServiceDefinition bindService(
      final QryAccountService serviceImpl) {
    return io.grpc.ServerServiceDefinition.builder(SERVICE_NAME)
        .addMethod(
          METHOD_QRY,
          asyncUnaryCall(
            new MethodHandlers<
              com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest,
              com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse>(
                serviceImpl, METHODID_QRY)))
        .build();
  }
}
View Code

QryAccountProto.java文件内容

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

package com.mzsg.demo.grpc.qryaccount;

public final class QryAccountProto {
  private QryAccountProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
  }
  public interface AccountQryRequestOrBuilder extends
      // @@protoc_insertion_point(interface_extends:accountService.AccountQryRequest)
      com.google.protobuf.MessageOrBuilder {

    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    java.lang.String getRequestId();
    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    com.google.protobuf.ByteString
        getRequestIdBytes();

    /**
     * <code>optional string userId = 2;</code>
     *
     * <pre>
     *用户ID
     * </pre>
     */
    java.lang.String getUserId();
    /**
     * <code>optional string userId = 2;</code>
     *
     * <pre>
     *用户ID
     * </pre>
     */
    com.google.protobuf.ByteString
        getUserIdBytes();
  }
  /**
   * Protobuf type {@code accountService.AccountQryRequest}
   *
   * <pre>
   *账户查询请求
   * </pre>
   */
  public  static final class AccountQryRequest extends
      com.google.protobuf.GeneratedMessage implements
      // @@protoc_insertion_point(message_implements:accountService.AccountQryRequest)
      AccountQryRequestOrBuilder {
    // Use AccountQryRequest.newBuilder() to construct.
    private AccountQryRequest(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
      super(builder);
    }
    private AccountQryRequest() {
      requestId_ = "";
      userId_ = "";
    }

    @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
    getUnknownFields() {
      return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
    }
    private AccountQryRequest(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry) {
      this();
      int mutable_bitField0_ = 0;
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!input.skipField(tag)) {
                done = true;
              }
              break;
            }
            case 10: {
              java.lang.String s = input.readStringRequireUtf8();

              requestId_ = s;
              break;
            }
            case 18: {
              java.lang.String s = input.readStringRequireUtf8();

              userId_ = s;
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw new RuntimeException(e.setUnfinishedMessage(this));
      } catch (java.io.IOException e) {
        throw new RuntimeException(
            new com.google.protobuf.InvalidProtocolBufferException(
                e.getMessage()).setUnfinishedMessage(this));
      } finally {
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryRequest_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryRequest_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.class, com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.Builder.class);
    }

    public static final int REQUESTID_FIELD_NUMBER = 1;
    private volatile java.lang.Object requestId_;
    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    public java.lang.String getRequestId() {
      java.lang.Object ref = requestId_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        requestId_ = s;
        return s;
      }
    }
    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    public com.google.protobuf.ByteString
        getRequestIdBytes() {
      java.lang.Object ref = requestId_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        requestId_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int USERID_FIELD_NUMBER = 2;
    private volatile java.lang.Object userId_;
    /**
     * <code>optional string userId = 2;</code>
     *
     * <pre>
     *用户ID
     * </pre>
     */
    public java.lang.String getUserId() {
      java.lang.Object ref = userId_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        userId_ = s;
        return s;
      }
    }
    /**
     * <code>optional string userId = 2;</code>
     *
     * <pre>
     *用户ID
     * </pre>
     */
    public com.google.protobuf.ByteString
        getUserIdBytes() {
      java.lang.Object ref = userId_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        userId_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

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

      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      if (!getRequestIdBytes().isEmpty()) {
        com.google.protobuf.GeneratedMessage.writeString(output, 1, requestId_);
      }
      if (!getUserIdBytes().isEmpty()) {
        com.google.protobuf.GeneratedMessage.writeString(output, 2, userId_);
      }
    }

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

      size = 0;
      if (!getRequestIdBytes().isEmpty()) {
        size += com.google.protobuf.GeneratedMessage.computeStringSize(1, requestId_);
      }
      if (!getUserIdBytes().isEmpty()) {
        size += com.google.protobuf.GeneratedMessage.computeStringSize(2, userId_);
      }
      memoizedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }

    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder() {
      return DEFAULT_INSTANCE.toBuilder();
    }
    public static Builder newBuilder(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest prototype) {
      return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() {
      return this == DEFAULT_INSTANCE
          ? new Builder() : new Builder().mergeFrom(this);
    }

    @java.lang.Override
    protected Builder newBuilderForType(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code accountService.AccountQryRequest}
     *
     * <pre>
     *账户查询请求
     * </pre>
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder> implements
        // @@protoc_insertion_point(builder_implements:accountService.AccountQryRequest)
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequestOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryRequest_descriptor;
      }

      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
          internalGetFieldAccessorTable() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryRequest_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.class, com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.Builder.class);
      }

      // Construct using com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        }
      }
      public Builder clear() {
        super.clear();
        requestId_ = "";

        userId_ = "";

        return this;
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryRequest_descriptor;
      }

      public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest getDefaultInstanceForType() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.getDefaultInstance();
      }

      public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest build() {
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest buildPartial() {
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest result = new com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest(this);
        result.requestId_ = requestId_;
        result.userId_ = userId_;
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest) {
          return mergeFrom((com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest other) {
        if (other == com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest.getDefaultInstance()) return this;
        if (!other.getRequestId().isEmpty()) {
          requestId_ = other.requestId_;
          onChanged();
        }
        if (!other.getUserId().isEmpty()) {
          userId_ = other.userId_;
          onChanged();
        }
        onChanged();
        return this;
      }

      public final boolean isInitialized() {
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest) e.getUnfinishedMessage();
          throw e;
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }

      private java.lang.Object requestId_ = "";
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public java.lang.String getRequestId() {
        java.lang.Object ref = requestId_;
        if (!(ref instanceof java.lang.String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          java.lang.String s = bs.toStringUtf8();
          requestId_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public com.google.protobuf.ByteString
          getRequestIdBytes() {
        java.lang.Object ref = requestId_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          requestId_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public Builder setRequestId(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  
        requestId_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public Builder clearRequestId() {
        
        requestId_ = getDefaultInstance().getRequestId();
        onChanged();
        return this;
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public Builder setRequestIdBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);
        
        requestId_ = value;
        onChanged();
        return this;
      }

      private java.lang.Object userId_ = "";
      /**
       * <code>optional string userId = 2;</code>
       *
       * <pre>
       *用户ID
       * </pre>
       */
      public java.lang.String getUserId() {
        java.lang.Object ref = userId_;
        if (!(ref instanceof java.lang.String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          java.lang.String s = bs.toStringUtf8();
          userId_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>optional string userId = 2;</code>
       *
       * <pre>
       *用户ID
       * </pre>
       */
      public com.google.protobuf.ByteString
          getUserIdBytes() {
        java.lang.Object ref = userId_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          userId_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>optional string userId = 2;</code>
       *
       * <pre>
       *用户ID
       * </pre>
       */
      public Builder setUserId(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  
        userId_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>optional string userId = 2;</code>
       *
       * <pre>
       *用户ID
       * </pre>
       */
      public Builder clearUserId() {
        
        userId_ = getDefaultInstance().getUserId();
        onChanged();
        return this;
      }
      /**
       * <code>optional string userId = 2;</code>
       *
       * <pre>
       *用户ID
       * </pre>
       */
      public Builder setUserIdBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);
        
        userId_ = value;
        onChanged();
        return this;
      }
      public final Builder setUnknownFields(
          final com.google.protobuf.UnknownFieldSet unknownFields) {
        return this;
      }

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


      // @@protoc_insertion_point(builder_scope:accountService.AccountQryRequest)
    }

    // @@protoc_insertion_point(class_scope:accountService.AccountQryRequest)
    private static final com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest DEFAULT_INSTANCE;
    static {
      DEFAULT_INSTANCE = new com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest();
    }

    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest getDefaultInstance() {
      return DEFAULT_INSTANCE;
    }

    private static final com.google.protobuf.Parser<AccountQryRequest>
        PARSER = new com.google.protobuf.AbstractParser<AccountQryRequest>() {
      public AccountQryRequest parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        try {
          return new AccountQryRequest(input, extensionRegistry);
        } catch (RuntimeException e) {
          if (e.getCause() instanceof
              com.google.protobuf.InvalidProtocolBufferException) {
            throw (com.google.protobuf.InvalidProtocolBufferException)
                e.getCause();
          }
          throw e;
        }
      }
    };

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

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

    public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest getDefaultInstanceForType() {
      return DEFAULT_INSTANCE;
    }

  }

  public interface AccountQryResponseOrBuilder extends
      // @@protoc_insertion_point(interface_extends:accountService.AccountQryResponse)
      com.google.protobuf.MessageOrBuilder {

    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    java.lang.String getRequestId();
    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    com.google.protobuf.ByteString
        getRequestIdBytes();

    /**
     * <code>optional int32 rc = 2;</code>
     *
     * <pre>
     *返回码,1:成功; -1:失败
     * </pre>
     */
    int getRc();

    /**
     * <code>optional string msg = 3;</code>
     *
     * <pre>
     *错误消息
     * </pre>
     */
    java.lang.String getMsg();
    /**
     * <code>optional string msg = 3;</code>
     *
     * <pre>
     *错误消息
     * </pre>
     */
    com.google.protobuf.ByteString
        getMsgBytes();

    /**
     * <code>optional int32 amount = 4;</code>
     *
     * <pre>
     *账户余额
     * </pre>
     */
    int getAmount();
  }
  /**
   * Protobuf type {@code accountService.AccountQryResponse}
   *
   * <pre>
   *账户查询响应
   * </pre>
   */
  public  static final class AccountQryResponse extends
      com.google.protobuf.GeneratedMessage implements
      // @@protoc_insertion_point(message_implements:accountService.AccountQryResponse)
      AccountQryResponseOrBuilder {
    // Use AccountQryResponse.newBuilder() to construct.
    private AccountQryResponse(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
      super(builder);
    }
    private AccountQryResponse() {
      requestId_ = "";
      rc_ = 0;
      msg_ = "";
      amount_ = 0;
    }

    @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
    getUnknownFields() {
      return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
    }
    private AccountQryResponse(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry) {
      this();
      int mutable_bitField0_ = 0;
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!input.skipField(tag)) {
                done = true;
              }
              break;
            }
            case 10: {
              java.lang.String s = input.readStringRequireUtf8();

              requestId_ = s;
              break;
            }
            case 16: {

              rc_ = input.readInt32();
              break;
            }
            case 26: {
              java.lang.String s = input.readStringRequireUtf8();

              msg_ = s;
              break;
            }
            case 32: {

              amount_ = input.readInt32();
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw new RuntimeException(e.setUnfinishedMessage(this));
      } catch (java.io.IOException e) {
        throw new RuntimeException(
            new com.google.protobuf.InvalidProtocolBufferException(
                e.getMessage()).setUnfinishedMessage(this));
      } finally {
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryResponse_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryResponse_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.class, com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.Builder.class);
    }

    public static final int REQUESTID_FIELD_NUMBER = 1;
    private volatile java.lang.Object requestId_;
    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    public java.lang.String getRequestId() {
      java.lang.Object ref = requestId_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        requestId_ = s;
        return s;
      }
    }
    /**
     * <code>optional string requestId = 1;</code>
     *
     * <pre>
     *请求流水
     * </pre>
     */
    public com.google.protobuf.ByteString
        getRequestIdBytes() {
      java.lang.Object ref = requestId_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        requestId_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int RC_FIELD_NUMBER = 2;
    private int rc_;
    /**
     * <code>optional int32 rc = 2;</code>
     *
     * <pre>
     *返回码,1:成功; -1:失败
     * </pre>
     */
    public int getRc() {
      return rc_;
    }

    public static final int MSG_FIELD_NUMBER = 3;
    private volatile java.lang.Object msg_;
    /**
     * <code>optional string msg = 3;</code>
     *
     * <pre>
     *错误消息
     * </pre>
     */
    public java.lang.String getMsg() {
      java.lang.Object ref = msg_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        msg_ = s;
        return s;
      }
    }
    /**
     * <code>optional string msg = 3;</code>
     *
     * <pre>
     *错误消息
     * </pre>
     */
    public com.google.protobuf.ByteString
        getMsgBytes() {
      java.lang.Object ref = msg_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        msg_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int AMOUNT_FIELD_NUMBER = 4;
    private int amount_;
    /**
     * <code>optional int32 amount = 4;</code>
     *
     * <pre>
     *账户余额
     * </pre>
     */
    public int getAmount() {
      return amount_;
    }

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

      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      if (!getRequestIdBytes().isEmpty()) {
        com.google.protobuf.GeneratedMessage.writeString(output, 1, requestId_);
      }
      if (rc_ != 0) {
        output.writeInt32(2, rc_);
      }
      if (!getMsgBytes().isEmpty()) {
        com.google.protobuf.GeneratedMessage.writeString(output, 3, msg_);
      }
      if (amount_ != 0) {
        output.writeInt32(4, amount_);
      }
    }

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

      size = 0;
      if (!getRequestIdBytes().isEmpty()) {
        size += com.google.protobuf.GeneratedMessage.computeStringSize(1, requestId_);
      }
      if (rc_ != 0) {
        size += com.google.protobuf.CodedOutputStream
          .computeInt32Size(2, rc_);
      }
      if (!getMsgBytes().isEmpty()) {
        size += com.google.protobuf.GeneratedMessage.computeStringSize(3, msg_);
      }
      if (amount_ != 0) {
        size += com.google.protobuf.CodedOutputStream
          .computeInt32Size(4, amount_);
      }
      memoizedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input, extensionRegistry);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }

    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder() {
      return DEFAULT_INSTANCE.toBuilder();
    }
    public static Builder newBuilder(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse prototype) {
      return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() {
      return this == DEFAULT_INSTANCE
          ? new Builder() : new Builder().mergeFrom(this);
    }

    @java.lang.Override
    protected Builder newBuilderForType(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code accountService.AccountQryResponse}
     *
     * <pre>
     *账户查询响应
     * </pre>
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder> implements
        // @@protoc_insertion_point(builder_implements:accountService.AccountQryResponse)
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponseOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryResponse_descriptor;
      }

      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
          internalGetFieldAccessorTable() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryResponse_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.class, com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.Builder.class);
      }

      // Construct using com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        }
      }
      public Builder clear() {
        super.clear();
        requestId_ = "";

        rc_ = 0;

        msg_ = "";

        amount_ = 0;

        return this;
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.internal_static_accountService_AccountQryResponse_descriptor;
      }

      public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse getDefaultInstanceForType() {
        return com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.getDefaultInstance();
      }

      public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse build() {
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse buildPartial() {
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse result = new com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse(this);
        result.requestId_ = requestId_;
        result.rc_ = rc_;
        result.msg_ = msg_;
        result.amount_ = amount_;
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse) {
          return mergeFrom((com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse other) {
        if (other == com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse.getDefaultInstance()) return this;
        if (!other.getRequestId().isEmpty()) {
          requestId_ = other.requestId_;
          onChanged();
        }
        if (other.getRc() != 0) {
          setRc(other.getRc());
        }
        if (!other.getMsg().isEmpty()) {
          msg_ = other.msg_;
          onChanged();
        }
        if (other.getAmount() != 0) {
          setAmount(other.getAmount());
        }
        onChanged();
        return this;
      }

      public final boolean isInitialized() {
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse) e.getUnfinishedMessage();
          throw e;
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }

      private java.lang.Object requestId_ = "";
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public java.lang.String getRequestId() {
        java.lang.Object ref = requestId_;
        if (!(ref instanceof java.lang.String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          java.lang.String s = bs.toStringUtf8();
          requestId_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public com.google.protobuf.ByteString
          getRequestIdBytes() {
        java.lang.Object ref = requestId_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          requestId_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public Builder setRequestId(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  
        requestId_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public Builder clearRequestId() {
        
        requestId_ = getDefaultInstance().getRequestId();
        onChanged();
        return this;
      }
      /**
       * <code>optional string requestId = 1;</code>
       *
       * <pre>
       *请求流水
       * </pre>
       */
      public Builder setRequestIdBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);
        
        requestId_ = value;
        onChanged();
        return this;
      }

      private int rc_ ;
      /**
       * <code>optional int32 rc = 2;</code>
       *
       * <pre>
       *返回码,1:成功; -1:失败
       * </pre>
       */
      public int getRc() {
        return rc_;
      }
      /**
       * <code>optional int32 rc = 2;</code>
       *
       * <pre>
       *返回码,1:成功; -1:失败
       * </pre>
       */
      public Builder setRc(int value) {
        
        rc_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>optional int32 rc = 2;</code>
       *
       * <pre>
       *返回码,1:成功; -1:失败
       * </pre>
       */
      public Builder clearRc() {
        
        rc_ = 0;
        onChanged();
        return this;
      }

      private java.lang.Object msg_ = "";
      /**
       * <code>optional string msg = 3;</code>
       *
       * <pre>
       *错误消息
       * </pre>
       */
      public java.lang.String getMsg() {
        java.lang.Object ref = msg_;
        if (!(ref instanceof java.lang.String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          java.lang.String s = bs.toStringUtf8();
          msg_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>optional string msg = 3;</code>
       *
       * <pre>
       *错误消息
       * </pre>
       */
      public com.google.protobuf.ByteString
          getMsgBytes() {
        java.lang.Object ref = msg_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          msg_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>optional string msg = 3;</code>
       *
       * <pre>
       *错误消息
       * </pre>
       */
      public Builder setMsg(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  
        msg_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>optional string msg = 3;</code>
       *
       * <pre>
       *错误消息
       * </pre>
       */
      public Builder clearMsg() {
        
        msg_ = getDefaultInstance().getMsg();
        onChanged();
        return this;
      }
      /**
       * <code>optional string msg = 3;</code>
       *
       * <pre>
       *错误消息
       * </pre>
       */
      public Builder setMsgBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);
        
        msg_ = value;
        onChanged();
        return this;
      }

      private int amount_ ;
      /**
       * <code>optional int32 amount = 4;</code>
       *
       * <pre>
       *账户余额
       * </pre>
       */
      public int getAmount() {
        return amount_;
      }
      /**
       * <code>optional int32 amount = 4;</code>
       *
       * <pre>
       *账户余额
       * </pre>
       */
      public Builder setAmount(int value) {
        
        amount_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>optional int32 amount = 4;</code>
       *
       * <pre>
       *账户余额
       * </pre>
       */
      public Builder clearAmount() {
        
        amount_ = 0;
        onChanged();
        return this;
      }
      public final Builder setUnknownFields(
          final com.google.protobuf.UnknownFieldSet unknownFields) {
        return this;
      }

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


      // @@protoc_insertion_point(builder_scope:accountService.AccountQryResponse)
    }

    // @@protoc_insertion_point(class_scope:accountService.AccountQryResponse)
    private static final com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse DEFAULT_INSTANCE;
    static {
      DEFAULT_INSTANCE = new com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse();
    }

    public static com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse getDefaultInstance() {
      return DEFAULT_INSTANCE;
    }

    private static final com.google.protobuf.Parser<AccountQryResponse>
        PARSER = new com.google.protobuf.AbstractParser<AccountQryResponse>() {
      public AccountQryResponse parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        try {
          return new AccountQryResponse(input, extensionRegistry);
        } catch (RuntimeException e) {
          if (e.getCause() instanceof
              com.google.protobuf.InvalidProtocolBufferException) {
            throw (com.google.protobuf.InvalidProtocolBufferException)
                e.getCause();
          }
          throw e;
        }
      }
    };

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

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

    public com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse getDefaultInstanceForType() {
      return DEFAULT_INSTANCE;
    }

  }

  private static com.google.protobuf.Descriptors.Descriptor
    internal_static_accountService_AccountQryRequest_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_accountService_AccountQryRequest_fieldAccessorTable;
  private static com.google.protobuf.Descriptors.Descriptor
    internal_static_accountService_AccountQryResponse_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_accountService_AccountQryResponse_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "
20AccountQry.proto2216accountService"6
21Ac" +
      "countQryRequest2221
	requestId3001 01(	2216
06us" +
      "erId3002 01(	"P
22AccountQryResponse2221
	requ" +
      "estId3001 01(	22

02rc3002 01(052213
03msg3003 01(	2216
06" +
      "amount3004 01(052a
21QryAccountService22L
03Qry" +
      "22!.accountService.AccountQryRequest32".ac" +
      "countService.AccountQryResponseB0
35com.m" +
      "zsg.demo.grpc.qryaccountB17QryAccountProt" +
      "ob06proto3"
    };
    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_accountService_AccountQryRequest_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_accountService_AccountQryRequest_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessage.FieldAccessorTable(
        internal_static_accountService_AccountQryRequest_descriptor,
        new java.lang.String[] { "RequestId", "UserId", });
    internal_static_accountService_AccountQryResponse_descriptor =
      getDescriptor().getMessageTypes().get(1);
    internal_static_accountService_AccountQryResponse_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessage.FieldAccessorTable(
        internal_static_accountService_AccountQryResponse_descriptor,
        new java.lang.String[] { "RequestId", "Rc", "Msg", "Amount", });
  }

  // @@protoc_insertion_point(outer_class_scope)
}
 

7、编写接口实现类QryAccountServiceImpl.java

package com.mzsg.demo.grpc.qryaccount.impl;

import com.mzsg.demo.grpc.qryaccount.QryAccountProto;
import com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest;
import com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse;
import com.mzsg.demo.grpc.qryaccount.QryAccountServiceGrpc.QryAccountService;

import io.grpc.stub.StreamObserver;

public class QryAccountServiceImpl implements QryAccountService {

    public void qry(AccountQryRequest request, StreamObserver<AccountQryResponse> responseObserver) {
        System.out.println("qry " + request.getUserId());
        AccountQryResponse response = QryAccountProto.AccountQryResponse.newBuilder().setRc(1).setAmount(666).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}
View Code

7、编写接口实现类QryAccountServiceImpl.java

 
package com.mzsg.demo.grpc.qryaccount.impl;

import com.mzsg.demo.grpc.qryaccount.QryAccountProto;
import com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest;
import com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse;
import com.mzsg.demo.grpc.qryaccount.QryAccountServiceGrpc.QryAccountService;

import io.grpc.stub.StreamObserver;

public class QryAccountServiceImpl implements QryAccountService {

    public void qry(AccountQryRequest request, StreamObserver<AccountQryResponse> responseObserver) {
        System.out.println("qry " + request.getUserId());
        AccountQryResponse response = QryAccountProto.AccountQryResponse.newBuilder().setRc(1).setAmount(666).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}


8、编码Server端代码Server.java

package com.mzsg.demo.grpc;

import java.io.IOException;

import com.mzsg.demo.grpc.qryaccount.QryAccountServiceGrpc;
import com.mzsg.demo.grpc.qryaccount.impl.QryAccountServiceImpl;

public class Server {

       private static int port = 8883;
        private static io.grpc.Server server;

        public void run() {
            QryAccountServiceGrpc.QryAccountService modifyAccountServiceImpl = new QryAccountServiceImpl();
            server = io.grpc.ServerBuilder.forPort(port).addService(QryAccountServiceGrpc.bindService(modifyAccountServiceImpl)).build();
            try {
                server.start();
                System.out.println("Server start success on port:" + port);
                server.awaitTermination();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        public static void main(String[] args) {
            Server server = new Server();
            server.run();
        }
}

9、编码Client端代码Client.java

package com.mzsg.demo.grpc;

import java.io.FileNotFoundException;
import java.io.IOException;

import com.mzsg.demo.grpc.qryaccount.QryAccountProto;
import com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryRequest;
import com.mzsg.demo.grpc.qryaccount.QryAccountProto.AccountQryResponse;
import com.mzsg.demo.grpc.qryaccount.QryAccountServiceGrpc;
import com.mzsg.demo.grpc.qryaccount.QryAccountServiceGrpc.QryAccountServiceBlockingStub;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class Client {
    public static void main( String[] args ) throws FileNotFoundException, IOException{
        AccountQryRequest request = QryAccountProto.AccountQryRequest.newBuilder().setUserId("20012").setRequestId("123").build();
        ManagedChannel channel = ManagedChannelBuilder
                  .forAddress("localhost", 8883)
                  .usePlaintext(true)
                  .build();
        QryAccountServiceBlockingStub stub = QryAccountServiceGrpc.newBlockingStub(channel);
        for (int j = 0; j < 20; j++) {
            long start = System.currentTimeMillis();
                for(int i=0; i<10000; i++){
                    AccountQryResponse rsp = stub.qry(request);
                    //System.out.println(rsp);
                }
                System.out.println(System.currentTimeMillis() - start + " MS");
            }
    }
}

10、运行Server.java,再运行Client.java

          简单性能对比(每万次调用消耗时间比):

  实现  时间(毫秒)  备注
  HTTP接口 13000   springboot+json,客户端采用HttpClient  
  Google Grpc   2100   本demo
  Facebook swift(Thrift)   1500   Thrift实现
欢迎转载,转载请务必注明出处
原文地址:https://www.cnblogs.com/mzsg/p/5643367.html