A tour of gRPC:06 - gRPC client straming 客户端流

在上一篇中,我们尝试了使用 server straming 的调用形式,在创建了十个 Laptop 并发送了一个筛选条 件后,由 server 多次返回符合筛选条件的结果,并且验证了这种调用形式的跨语言调用能力。在本篇 中,我们将尝试使用 client straming 即 client 发送多次内容,而 server 在接收完所以内容后,返回一次 响应。本次我们将利用 client straming 这种调用形式实现图像传输的功能
go Client Straming call
1. 修改 laptop_sercice.proto 增加三个和上传图片相关的 message 和一个 rpc 函数,运行 make gen 生成代码

2. 在 service 下新建 image_store.go 实现一个图像存储

3. 在 laptop_server.go 下添加 imageStore 内容,并在 NewLaptopServer 中新增一个参数

4. 将所有用到 NewLaptopServer 和 store 的位置进行一下修改(test 和 main),运行一次单元测试
5. 实现 laptop_server 中的 UploadImage

6. 重构、修改 client 包下的 main 代码

7. 在 server 包下的 main.go 代码

8. 编写一个单元测试进行测试

我们在项目的根目录下新建一个 tmp 文件夹,并存放一张命名为 images.jpeg 的图片。接下来,启动 server 和 client 尝试进行传输。



文件被正确且成功的传输了。观察 server 的 log 可以发现,如我们预期,图片是被分割发送的。我们可以计算一下 ,图片大小为 6164,传输时分成了 6 个 1024k 和 1 个 20k
Java Client Straming
1. 复制 go client Straming 中的 laptop_service.proto 运行 mvn clean complie 对生成的代 码进行更新
2. 在 service 包下 创建一个 ImageStore interface

3. 在 service 包下 创建 ImageSotre 实体类

4. 在 service 包下 创建 DiskImageStore 实现上面的 ImageStore

5. 在 LaptopService 下实现 uploadImage

6. 修改 LaptopServer 中的 main 添加图片上传的内容

7. 运行 Java 的 server 再运行 golang 的 client 可以看到 img 文件下收到了 golang 客户端发来的图片
8. 修改 LaptopClient 并添加 Java 客户端内容

9. 修改 LaptopService 增加一个最大上传限制

同上,我们运行测试一下


同样,文件被正确且成功的传输了。观察 server 的 log 可以发现,如我们预期,图片是被分割发送的。计算一下 ,图片大小为 6164k ,传输时分成了 6 个 1024k 和 1 个 20k
跨语言的 client straming call 测试
1. 运行 Java 的 server ,再运行 golang 的 client

2. 运行 go 的 server ,再运行 Java 的 client




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