【RPC基础系列3】gRPC简单示例

简介: 我们不能只看原理,而忽略实践,也不能只关注实践,而忽略原理,应该两者兼顾!前面两篇文章《【RPC基础系列1】聊聊RPC》、《【RPC基础系列2】一文搞懂gRPC和Thrift的基本原理和区别》就能基本搞懂三个重要概念:RPC、gRPC和Thrift,这篇文章我们就看gPRC的使用姿势。

}K4PYA6}Q)7[9D%`VZ[CJQ2.jpg

本文主要讲述Java使用gRPC的简单示例。


前言


我们不能只看原理,而忽略实践,也不能只关注实践,而忽略原理,应该两者兼顾!

前面两篇文章《【RPC基础系列1】聊聊RPC》、《【RPC基础系列2】一文搞懂gRPC和Thrift的基本原理和区别》就能基本搞懂三个重要概念:RPC、gRPC和Thrift,这篇文章我们就看gPRC的使用姿势。


gRPC示例


代码:git@github.com:lml200701158/rpc-study.git


项目结构

我们先看一下项目结构:

)5Z}GULM~LD0@TI5{MEW3K8.pngimage.gif

生成protobuf文件

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;
}

这里提供了一个SayHello()方法,然后入参为HelloRequest,返回值为HelloReply,可以看到proto文件只定义了入参和返回值的格式,以及调用的接口,至于接口内部的实现,该文件完全不用关心。

pom.xml

<?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">
    <parent>
        <artifactId>rpc-study</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>grpc-demo</artifactId>
    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.14.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.14.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.14.0</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.5.1-1:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.14.0: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>
</project>


这里面的build其实是为了安装protobuf插件,里面其实有2个插件我们需要用到,分别为protobuf:compile和protobuf:compile-javanano,当我们直接执行时,会生成左侧文件,其中GreeterGrpc提供调用接口,Hello开头的文件功能主要是对数据进行序列化,然后处理入参和返回值。

可能有同学会问,你把文件生成到target中,我想放到main.src中,你可以把这些文件copy出来,或者也可以通过工具生成:

AM]]VL11X`$3$EX@HBY$0)3.png


服务端和客户端

HelloWorldClient.java

public class HelloWorldClient {
    private final ManagedChannel channel;
    private final GreeterGrpc.GreeterBlockingStub blockingStub;
    private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
    public HelloWorldClient(String host,int port){
        channel = ManagedChannelBuilder.forAddress(host,port)
                .usePlaintext(true)
                .build();
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }
    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }
    public  void greet(String 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("Message from gRPC-Server: "+response.getMessage());
    }
    public static void main(String[] args) throws InterruptedException {
        HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051);
        try{
            String user = "world";
            if (args.length > 0){
                user = args[0];
            }
            client.greet(user);
        }finally {
            client.shutdown();
        }
    }
}


这个太简单了,就是连接服务端口,调用sayHello()方法。

HelloWorldServer.java

public class HelloWorldServer {
    private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
    private int port = 50051;
    private Server server;
    private void start() throws IOException {
        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() {
                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();
        }
    }
    // block 一直到退出程序
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }
    // 实现 定义一个实现服务接口的类
    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();
            System.out.println("Message from gRPC-Client:" + req.getName());
            System.out.println("Message Response:" + reply.getMessage());
        }
    }
}

主要是实现sayHello()方法,里面对数据进行了简单处理,入参为“W  orld”,返回的是“Hello World”


启动服务

先启动Server,返回如下:

RBQYXJEYO{G73%KRSJH){7U.png

再启动Client,返回如下:

MV[07(U2R[E@G1EQRG_Z)XW.png

同时Server返回如下:

NHAJ`WQ0A$%2T1{`AB%INIX.png


后记


这个Demo看起来很简单,我TM居然搞了大半天,一开始是因为不知道需要执行2个不同的插件来生成protobuf,以为只需要点击protobuf:compile就可以,结果发现protobuf:compile-javanano也需要点一下。


还有就是我自己喜欢作,感觉通过插件生成protobuf不完美,我想通过自己下载的插件,手动生成protobuf文件,结果手动生成的没有搞定,自动生成的方式也不可用,搞了半天才发现是缓存的问题,最后直接执行“Invalidate Caches / Restart”才搞定。


应征了一句话“no zuo no die”,不过这个过程还是需要经历的。

相关文章
|
4月前
|
缓存 网络协议 安全
计算机网络 TCP、RPC、GRPC、HTTP 对比
【1月更文挑战第1天】计算机网络 TCP、RPC、GRPC、HTTP 对比
|
11月前
|
编解码 中间件 Go
Go语言学习 - RPC篇:gRPC拦截器剖析
我们在前几讲提到过,优秀的RPC框架都提供了`middleware`的能力,可以减少很多重复代码的编写。在gRPC-Gateway的方案里,包括了两块中间件的能力: 1. gRPC中的`ServerOption`,是所有gRPC+HTTP都会被处理 2. gRPC-Gateway中的`ServeMuxOption`,只有HTTP协议会被处理 今天,我们先关注共同部分的`ServerOption`,它提供的能力最为全面,让我们一起了解下。
69 0
|
11天前
|
前端开发 C# 开发者
WPF开发者必读:MVVM模式实战,轻松构建可维护的应用程序,让你的代码更上一层楼!
【8月更文挑战第31天】在WPF应用程序开发中,MVVM(Model-View-ViewModel)模式通过分离关注点,提高了代码的可维护性和可扩展性。本文详细介绍了MVVM模式的三个核心组件:Model(数据模型)、View(用户界面)和ViewModel(处理数据绑定与逻辑),并通过示例代码展示了如何在WPF项目中实现MVVM模式。通过这种模式,开发者可以更高效地构建桌面应用程序。希望本文能帮助你在WPF开发中更好地应用MVVM模式。
32 0
|
18天前
|
网络协议 编译器 Go
揭秘!TCP、RPC、gRPC、HTTP大PK,谁才是网络通信界的超级巨星?一篇文章带你秒懂!
【8月更文挑战第25天】本文以教程形式深入对比了TCP、RPC、gRPC与HTTP这四种关键通信协议,并通过Go语言中的示例代码展示了各自的实现方法。TCP作为一种可靠的传输层协议,确保了数据的完整性和顺序性;RPC与gRPC作为远程过程调用框架,特别适合于分布式系统的函数调用与数据交换,其中gRPC在性能和跨语言支持方面表现出色;HTTP则是广泛应用于Web浏览器与服务器通信的应用层协议。选择合适的协议需根据具体需求综合考量。
89 0
|
3月前
|
存储 C++
gRPC 四模式之 双向流RPC模式
gRPC 四模式之 双向流RPC模式
90 0
|
3月前
|
安全 C++
gRPC 四模式之 客户端流RPC模式
gRPC 四模式之 客户端流RPC模式
36 0
|
3月前
|
C++
gRPC 四模式之 服务器端流RPC模式
gRPC 四模式之 服务器端流RPC模式
67 0
|
3月前
|
JSON API 数据格式
gRPC 四模式之 一元RPC模式
gRPC 四模式之 一元RPC模式
27 0
|
4月前
|
Dubbo Java 应用服务中间件
grpc&rpc
grpc&rpc
|
4月前
|
网络协议 安全 API
计算机网络 TCP、RPC、GRPC、HTTP 总结
【1月更文挑战第1天】计算机网络 TCP、RPC、GRPC、HTTP 总结