A tour of gRPC:04 - gRPC unary call 一元调用

在上一篇中,我们尝试了 proto 的序列化功能,并尝试进行了跨语言的序列化。而在本篇中,我们将尝 试实现一个简单的 gRPC 一元调用(unary call),通过 client 调用 server 的创建方法创建一个 Laptop 对 象,并存储在 server 的内存中,并同样尝试跨语言的调用。
go unary call
1. 编写一个 laptop_service.proto,让 proto 帮助我们生成 stub

该 proto 包含三个部分
CreateLaptopRequest (创建请求)
CreateLaptopResponse (创建响应)
LaptopService(laptop 相关服务) · CreateLaptop (包括请求参数和返回参数)
2. 运行 make gen 将该服务进行生成 laptop_service.pb.go
3. 由于本次重点是 grpc 不是数据库存储,这里使用内存存储数据,新建一个 service 包编写一个 laptop_store.go 进行解耦。

4. 编写 laptop 服务类 laptop_server.go 作为服务端的实现

5. 编写 laptop_server_test.go 作为 server 的测试类

我们来用这个单元测试,测试一下 server 端的创建方法是否正常的运行了。可以看到
有 id、无 id、非法 id、重复 id 的情况均符合测试预期

测试结果运行正常。
6. 编写 laptop_client_test.go 作为 client 的测试类

运行测试,成功启动了 server 并通过 client 的调用创建了一个 laptop

7. 好了,接下来我们为 client 和 server 各编写一个启动类
a. main/client/main.go 作为 client 的启动类

b. main/server/main.go 作为 client 的启动类

c. 修改 Makefile 增加 client 和 server 的快捷启动

8.运行服务端、再运行客户端,修改 clien 创建 laptop 的 id 内容,进行如下测试
client 携带 id 【成功】
client 不携带 id 【成功】
client 携带非法 id 【失败】
client 携带重复 id 【失败】

运行结果均符合预期。
Java unary call
1. 拷⻉之前在 go 项目中编写的 laptop_service.proto 并生成代码
2. 同 go 由于这里先不使用数据库(专注于 grpc)所以编写一个 LaptopStore 接口 和一个 InMemoryLaptopStore 实现类,用于解耦。
a. LaptopStore interface

b. InMemoryLaptopStore 实现类

3. 接着在 server 包下编写 LaptopServer 服务类

4. 在 service 包下编写 LaptopClient 作为 client 的启动类

5. 在 service 包下编写 LaptopServer 作为 server 的启动类

6. 同样编写一个服务端的单元测试类 LaptopServerTest


测试的结果符合预期
好了,接下来我们同 golang 项目一样,运行服务端、再运行客户端,修改 clien 创建 laptop 的 id 内容, 进行如下测试:client 携带 id 【成功】、client 不携带 id 【成功】、client 携带非法 id 【失败】client 携 带重复 id 【失败】
测试结果同上,这里就不进行展示了。
跨语言的 unary call 测试
我们先启动 Java 的 Server 再运行 golang 的 client,同样进行上述的测试:client 携带 id 【成功】、client 不携带 id 【成功】、client 携带非法 id 【失败】client 携带重复 id 【失败】

测试的结果符合预期。
我们不妨再反过来测试一下,使用 golang 的 server 和 Java 的 client





测试的结果同样符合预期,没有任何问题。在本篇中,我们实现了 gRPC 中的 unary call 并且初步尝试了 gRPC 的跨语言调用能力。



版权声明: 本文为 InfoQ 作者【BUG侦探】的原创文章。
原文链接:【http://xie.infoq.cn/article/270fa2f7bab914be26e89b585】。文章转载请联系作者。
评论