Grpc入门整理

1.Protobuf3入门学习文档 

本文是对Protobuf3(以下简称pb)官方文档的学习笔记,大部分示例摘自官方。

原文:https://developers.google.com/protocol-buffers/docs/proto3

一个简单的例子

syntax = "proto3";

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}

版本号

对于一个pb文件而言,文件首个非空、非注释的行必须注明pb的版本,即syntax = "proto3";,否则默认版本是proto2。

Message

一个message类型看上去很像一个Java class,由多个字段组成。每一个字段都由类型、名称组成,位于等号右边的值不是字段默认值,而是数字标签,可以理解为字段身份的标识符,类似于数据库中的主键,不可重复,标识符用于在编译后的二进制消息格式中对字段进行识别,一旦你的pb消息投入使用,字段的标识就不应该再改变。数字标签的范围是[1, 536870911],其中19000~19999是保留数字。

类型

每个字段的类型(int32,string)都是scalar的类型,和其他语言类型的对比如下:

 

修饰符

如果一个字段被repeated修饰,则表示它是一个列表类型的字段,如下所示:

...
message SearchRequest {
  repeated string args = 1 // 等价于java中的List<string> args
}

如果你希望可以预留一些数字标签或者字段可以使用reserved修饰符:

message Foo {
  reserved 2, 15, 9 to 11;
  reserved "foo", "bar";
  string foo = 3 // 编译报错,因为‘foo’已经被标为保留字段
}

默认值

  1. string类型的默认值是空字符串
  2. bytes类型的默认值是空字节
  3. bool类型的默认值是false
  4. 数字类型的默认值是0
  5. enum类型的默认值是第一个定义的枚举值
  6. message类型(对象,如上文的SearchRequest就是message类型)的默认值与 语言 相关
  7. repeated修饰的字段默认值是空列表

如果一个字段的值等于默认值(如bool类型的字段设为false),那么它将不会被序列化,这样的设计是为了节省流量。

枚举

每个枚举值有对应的数值,数值不一定是连续的。第一个枚举值的数值必须是0且至少有一个枚举值,否则编译报错。编译后编译器会为你生成对应语言的枚举类。

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
  enum Corpus {
    UNIVERSAL = 0;
    WEB = 1;
    IMAGES = 2;
    LOCAL = 3;
    NEWS = 4;
    PRODUCTS = 5;
    VIDEO = 6;
  }
  Corpus corpus = 4;
}

一个数值可以对应多个枚举值,必须标明option allow_alias = true;

enum EnumAllowingAlias {
  option allow_alias = true;
  UNKNOWN = 0;
  STARTED = 1;
  RUNNING = 1;
}

可以使用MessageType.EnumType的形式引用定义在其它message类型中的枚举。

由于编码原因,出于效率考虑,官方不推荐使用负数作为枚举值的数值。

使用其它的message类型

除了上述基本类型,一个字段的类型也可以是其它的message类型:

message SearchResponse {
  repeated Result results = 1;
}

message Result {
  string url = 1;
  string title = 2;
  repeated string snippets = 3;
}

从上面的例子可以看到,一个.proto文件中可以定义多个message。我们也可以引用定义在其它文件中的message:

import "myproject/other_protos.proto"; // 这样就可以引用在other_protos.proto文件中定义的message

不能导入不使用的.proto文件。

import还有一种特殊的语法,先看下面的例子:

// new.proto
// 原来在old.proto文件中的定义移到这里

 

// old.proto
import public "new.proto"; // 把引用传递给上层使用方
import "other.proto"; // 引用old.proto本身使用的定义
// client.proto
import "old.proto";
// 此处可以引用old.proto和new.proto中的定义,但不能使用other.proto中的定义

从这个例子中可以看到import关键字导入的定义仅在当前文件有效,不能被上层使用方引用(client.proto无法使用other.proto中的定义),而import public关键字导入的定义可以被上层使用方引用(client.proto可以使用new.proto中的定义),import public的功能可以看作是import的超集,在import的功能上还具有传递引用的作用。

嵌套类型

你可以在一个message类型中定义另一个message类型,并且可以一直嵌套下去,类似Java的内部类:

message SearchResponse {
  message Result {
    string url = 1;
    string title = 2;
    repeated string snippets = 3;
  }
  repeated Result results = 1;
}

可以使用Parent.Type的形式引用嵌套的message:

message SomeOtherMessage {
  SearchResponse.Result result = 1;
}

Any

Any类型允许包装任意的message类型:

import "google/protobuf/any.proto";

message Response {
    google.protobuf.Any data = 1;
}

可以通过pack()unpack()(方法名在不同的语言中可能不同)方法装箱/拆箱,以下是Java的例子:

People people = People.newBuilder().setName("proto").setAge(1).build();
// protoc编译后生成的message类
Response r = Response.newBuilder().setData(Any.pack(people)).build();
// 使用Response包装people

System.out.println(r.getData().getTypeUrl());
// type.googleapis.com/example.protobuf.people.People
System.out.println(r.getData().unpack(People.class).getName());
// proto

Any对包装的类型会生成一个URL,默认是type.googleapis.com/packagename.messagename(在Java中可以通过这个特性进行反射操作)。

Oneof

如果你有一些字段同时最多只有一个能被设置,可以使用oneof关键字来实现,任何一个字段被设置,其它字段会自动被清空(被设为默认值):

message SampleMessage {
  oneof test_oneof {
    string name = 4;
    SubMessage sub_message = 9;
  }
}

oneof块中的字段不支持repeated

Maps

pb中也可以使用map类型(官方并不认为是一种类型,此处称之为类型仅便于理解),绝大多数scalar类型都可以作为key,除了浮点型和bytes,枚举型也不能作为key,value可以是除了map以外的任意类型:

// map<key_type, value_type> map_field = N;
map<string, Project> projects = 3;

map类型字段不支持repeated,value的顺序是不定的。

map其实是一种语法糖,它等价于以下形式:

message MapFieldEntry {
  key_type key = 1;
  value_type value = 2;
}

repeated MapFieldEntry map_field = N;

你可以用指定package以避免类型命名冲突:

package foo.bar;
message Open { ... }

然后可以用类型的全限定名来引用它:

message Foo {
  ...
  foo.bar.Open open = 1;
  ...
}

指定包名后,会对生成的代码产生影响,以Java为例,生成的类会以你指定的package作为包名。

JSON映射

pb支持和JSON互相转换。如果一个字段不存在JSON数据中或者为null,那么pb中会被赋为该字段的默认值,反之,如果一个字段在pb中是默认值,那么不会写到JSON数据中以节省空间。

选项

选项不对message的定义产生任何的效果,只会在一些特定的场景中起到作用,下面是一部分例子,完整的选项列表可以前往google/protobuf/descriptor.proto查看(Java语言可以在jar包中找到):

  1. option java_package = "com.example.foo"; 编译器为以此作为生成的Java类的包名,如果没有该选项,则会以pb的package作为包名。
  2. option java_multiple_files = true; 该选项为true时,生成的Java类将是包级别的,否则会在一个包装类中。
  3. option optimize_for = CODE_SIZE; 该选项会对生成的类产生影响,作用是根据指定的选项对代码进行不同方面的优化。
  4. int32 old_field = 6 [deprecated=true]; 把字段标为过时的。

Java例子

最后,用Java写了一个简单的例子:Github

作者:宇宙最强架构师
链接:https://www.jianshu.com/p/ea656dc9b037
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

2.IDEA java开发 grpc框架的服务端和客户端--helloworld实例

参考:

  1. java下使用gRPC的helloworld的demo实现https://blog.csdn.net/u013992365/article/details/81698531#%E6%96%B0%E5%BB%BA%E4%B8%80%E4%B8%AA%E6%99%AE%E9%80%9A%E7%9A%84maven%E9%A1%B9%E7%9B%AE
  2. grpc官方文档中文版 http://doc.oschina.net/grpc?t=58008
  3. 示例:https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples

具体实施步骤:

1、新建一个普通的Maven项目:

点击下一步,再点击Finsh。

2、配置pom文件,导入grpc的依赖和插件

全部的pom内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<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.grpcprojects</groupId>
    <artifactId>grpcExercise3</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <properties>
        <grpc-version>1.20.0</grpc-version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-core</artifactId>
            <version>${grpc-version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>${grpc-version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>${grpc-version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>${grpc-version}</version>
        </dependency>
    </dependencies>
 
    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.5.0.Final</version>
            </extension>
        </extensions>
 
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}</pluginArtifact>
                    <protoSourceRoot>src/main/proto</protoSourceRoot>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
</project>

添加好依赖之后的显示:

添加之后选择右下键出现的import change,就能在Maven Projects中看到添加的依赖了。

3、编写helloworld.proto文件

在项目main目录下新建一个proto文件夹,再在此文件夹下创建一个helloworld.proto文件

helloworld.proto(跟官网上的一样)中的代码如下:

syntax = "proto3";
 
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
 
package helloworld;
 
// The greeting service definition.
service Greeter {
    // Sends a greeting
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}
 
// The request message containing the user's name.
message HelloRequest {
    string name = 1;
}
 
// The response message containing the greetings
message HelloReply {
    string message = 1;
}

编译helloworld.proto文件,编译此文件有两种方法,第一种使用protoc.exe和protoc-gen-grpc-java插件进行编译。第二种方法是用刚才在项目里边添加的插件进行编译。

第一种:使用protoc.exe和protoc-gen-grpc-java插件进行编译

下载protoc.exe 工具 , 下载地址:https://github.com/protocolbuffers/protobuf/releases

 下载protoc-gen-grpc 插件  , 下载地址: http://jcenter.bintray.com/io/grpc/protoc-gen-grpc-java/

将protoc.exe和protoc-gen-grpc插件放到main目录中:

在项目的terminal窗口中执行如下两条指令:

执行完每条指令之后,窗口应该不会出现任何信息,在项目文件目录中会添加如下文件:

第二种方法:用刚才在项目里边添加的插件进行编译

在分割线下边

4、添加客户端和服务端代码

我是直接从官网上直接拿过来的代码,分别为HelloWorldClient.java和HelloWorldServer.java

HelloWorldClient.java代码如下:

/*
 * Copyright 2015 The gRPC Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package helloworld;
 
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
 
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 * A simple client that requests a greeting from the {@link HelloWorldServer}.
 */
public class HelloWorldClient {
  private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
 
  private final ManagedChannel channel;
  private final GreeterGrpc.GreeterBlockingStub blockingStub;
 
  /** Construct client connecting to HelloWorld server at {@code host:port}. */
  public HelloWorldClient(String host, int port) {
    this(ManagedChannelBuilder.forAddress(host, port)
        // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
        // needing certificates.
        .usePlaintext()
        .build());
  }
 
  /** Construct client for accessing HelloWorld server using the existing channel. */
  HelloWorldClient(ManagedChannel channel) {
    this.channel = channel;
    blockingStub = GreeterGrpc.newBlockingStub(channel);
  }
 
  public void shutdown() throws InterruptedException {
    channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
  }
 
  /** Say hello to server. */
  public void greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    try {
      response = blockingStub.sayHello(request);
    } catch (StatusRuntimeException e) {
      logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
      return;
    }
    logger.info("Greeting: " + response.getMessage());
  }
 
  /**
   * Greet server. If provided, the first element of {@code args} is the name to use in the
   * greeting.
   */
  public static void main(String[] args) throws Exception {
    HelloWorldClient client = new HelloWorldClient("localhost", 50051);
    try {
      /* Access a service running on the local machine on port 50051 */
      String user = "world";
      if (args.length > 0) {
        user = args[0]; /* Use the arg as the name to greet if provided */
      }
      client.greet(user);
    } finally {
      client.shutdown();
    }
  }
}

HelloWorldServer.java代码如下:

/*
 * Copyright 2015 The gRPC Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package helloworld;
 
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.logging.Logger;
 
/**
 * Server that manages startup/shutdown of a {@code Greeter} server.
 */
public class HelloWorldServer {
  private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
 
  private Server server;
 
  private void start() throws IOException {
    /* The port on which the server should run */
    int port = 50051;
    server = ServerBuilder.forPort(port)
        .addService(new GreeterImpl())
        .build()
        .start();
    logger.info("Server started, listening on " + port);
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        // Use stderr here since the logger may have been reset by its JVM shutdown hook.
        System.err.println("*** shutting down gRPC server since JVM is shutting down");
        HelloWorldServer.this.stop();
        System.err.println("*** server shut down");
      }
    });
  }
 
  private void stop() {
    if (server != null) {
      server.shutdown();
    }
  }
 
  /**
   * Await termination on the main thread since the grpc library uses daemon threads.
   */
  private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
      server.awaitTermination();
    }
  }
 
  /**
   * Main launches the server from the command line.
   */
  public static void main(String[] args) throws IOException, InterruptedException {
    final HelloWorldServer server = new HelloWorldServer();
    server.start();
    server.blockUntilShutdown();
  }
 
  static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
 
    @Override
    public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
      HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
      responseObserver.onNext(reply);
      responseObserver.onCompleted();
    }
  }
}

5、最终的文件结构

6、执行服务端和客户端代码

先执行HelloWorldServer.java,再HelloWorldClient.java,得如下运行结果,正面我们的gprc通信成功了。

服务端显示如下:

客户端显示如下:



步骤1,2和上边完全相同,此处从步骤3的第二种方法开始说。

第二种方法:用刚才在项目里边添加的插件进行编译。

  • 右击Maven.Projects\protobuf\protobuf:compile ,选择run,生成用于序列化的java文件。
  • 再右击Maven.Projects\protobuf\protobuf:compile-custom,选择run,生成用于rpc的java代码。

执行完这两步,会产生的文件为:

但是在执行这两步的过程中,控制台会出现报错的信息,但是在后边服务端和客户端运行的时候并没有报别的错误。

哪位大佬能解决这个问题,麻烦请告知一下,多谢了。

4、客户端和服务端的代码和上边写的一样

5、项目文件目录如下:

6、最后的运行结果(和上边的运行结果一样,并没有报错误)

服务端的显示:

客户端的显示:

引自:https://blog.csdn.net/qq_29319189/article/details/93539198

3.gRPC 中泛化调用服务接口

https://blog.csdn.net/u013360850/article/details/115414627

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值