前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >gRPC示例初探【实战笔记】

gRPC示例初探【实战笔记】

作者头像
瓜农老梁
发布2019-11-12 22:14:24
7560
发布2019-11-12 22:14:24
举报
文章被收录于专栏:瓜农老梁瓜农老梁
目录
代码语言:javascript
复制
一、运行示例代码
1.下载源代码
2.编译Client和Server
3.运行Server
4.运行Client
二、增加方法示例
1.proto在中增加SayHelloAgain方法
2.Server端实现sayHelloAgain方法
3.Client端增加调用方法
4.运行示例
三、Maven项目中运行示例
1.添加依赖和proto生成代码插件
2.运行工程示例
四、小结五、系列文章
一、运行示例代码
1.下载源代码
代码语言:javascript
复制
git clone -b v1.25.0 https://github.com/grpc/grpc-java
cd grpc-java/examples
2.编译Client和Server
代码语言:javascript
复制
./gradlew installDist

BUILD SUCCESSFUL in 1s
14 actionable tasks: 9 executed, 5 up-to-date
3.运行Server
代码语言:javascript
复制
./build/install/examples/bin/hello-world-server
十一月 10, 2019 3:55:16 下午 io.grpc.examples.helloworld.HelloWorldServer start
信息: Server started, listening on 50051
4.运行Client
代码语言:javascript
复制
./build/install/examples/bin/hello-world-client
十一月 10, 2019 4:05:00 下午 io.grpc.examples.helloworld.HelloWorldClient greet
信息: Will try to greet world ...
十一月 10, 2019 4:05:01 下午 io.grpc.examples.helloworld.HelloWorldClient greet
信息: Greeting: Hello world

备注:Will try to greet world ...这条日志在Client端访问Server前打印;Greeting: Hello world 这条日志在Server返回给Client后打印。

二、增加方法示例

1.proto在中增加SayHelloAgain方法

代码位置:src/main/proto/helloworld.proto

代码语言:javascript
复制
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (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;
}

编译后会在GreeterImplBase类中生成sayHelloAgain方法内容如下:

代码语言:javascript
复制
public void sayHelloAgain(io.grpc.examples.helloworld.HelloRequest request,
        io.grpc.stub.StreamObserver<io.grpc.examples.helloworld.HelloReply> responseObserver) {
      asyncUnimplementedUnaryCall(getSayHelloAgainMethod(), responseObserver);
}
2.Server端实现sayHelloAgain方法

代码位置:

src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java

代码语言:javascript
复制
private 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();
  }

  @Override
  public void sayHelloAgain(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello again " + req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }
}
3.Client端增加调用方法

代码位置:src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java

代码语言:javascript
复制
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());
  try {
    response = blockingStub.sayHelloAgain(request);
  } catch (StatusRuntimeException e) {
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }
  logger.info("Greeting: " + response.getMessage());
}
4.运行示例
编译Client和Server
代码语言:javascript
复制
./gradlew installDist

> Task :compileJava
警告: [options] 未与 -source 1.7 一起设置引导类路径
1 个警告

BUILD SUCCESSFUL in 1s
14 actionable tasks: 3 executed, 11 up-to-date
运行Server
代码语言:javascript
复制
./build/install/examples/bin/hello-world-server
十一月 10, 2019 4:53:53 下午 io.grpc.examples.helloworld.HelloWorldServer start
信息: Server started, listening on 50051
运行Client
代码语言:javascript
复制
./build/install/examples/bin/hello-world-client
十一月 10, 2019 4:53:56 下午 io.grpc.examples.helloworld.HelloWorldClient greet
信息: Will try to greet world ...
十一月 10, 2019 4:53:57 下午 io.grpc.examples.helloworld.HelloWorldClient greet
信息: Greeting: Hello world
十一月 10, 2019 4:53:57 下午 io.grpc.examples.helloworld.HelloWorldClient greet
信息: Greeting: Hello again world

Server端新增的SayHelloAgain被执行,返回给客户端并打印。

三、Maven项目中运行示例
1.添加依赖和proto生成代码插件
代码语言:javascript
复制
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <grpc.version>1.25.0</grpc.version><!-- CURRENT_GRPC_VERSION -->
    <protobuf.version>3.10.0</protobuf.version>
    <protoc.version>3.10.0</protoc.version>
</properties>

 <dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty-shaded</artifactId>
    <version>1.25.0</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>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java-util</artifactId>
    <version>${protobuf.version}</version>
</dependency>

<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.6.2</version>
        </extension>
    </extensions>
    <plugins>
        <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.6.1</version>
            <configuration>
                <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
            </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>
            <configuration>
                <source>6</source>
                <target>6</target>
            </configuration>
        </plugin>
    </plugins>
</build>

备注:将上面例子中的helloworld.proto拷贝到该工程下,在编译时在target下自动生成相应的代码,将生成的代码拷贝到工程里,并将上面示例中的Client实现HelloWorldClient和Server端实现类HelloWorldServer拷贝到工程中。结构如下所示:

2.运行工程示例

Server运行
Client运行
四、小结

本文从官方给出的gRPC-java示例开始,从命令行和项目工程两种方式来运行Client向Server端调用示例,对gRPC有较直观的印象。


本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 瓜农老梁 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目录
  • 一、运行示例代码
  • 1.下载源代码
  • 2.编译Client和Server
  • 3.运行Server
  • 4.运行Client
  • 1.proto在中增加SayHelloAgain方法
  • 2.Server端实现sayHelloAgain方法
  • 3.Client端增加调用方法
  • 4.运行示例
  • 编译Client和Server
  • 运行Server
  • 运行Client
  • 三、Maven项目中运行示例
  • 1.添加依赖和proto生成代码插件
  • Server运行
  • Client运行
  • 四、小结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档