使用Java搭建gRPC服务端
1、如何配置Maven
方式一:
io.grpc grpc-all 1.26.0
方式二:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 <dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.44.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.44.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.44.0</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
map[key_type]value_typego
io.grpc grpc-netty 1.26.0 io.grpc grpc-protobuf 1.26.0 io.grpc grpc-stub 1.26.0
三种方式的区别:
a.
方式一会把与gRPC相关的所有jar都引入,不管实际项目中是否会用到。引入相关jar较多,但其配置简单。
方式三只会引入与gRPC和netty相关的jar,如果要使用OkHttp,则要再引入。配置相对较多,但引入jar相对较少。
方式二引入的jar的数量介于方式一与方式三之间。
b.
方式一中netty是以原始jar引用的。这样方便在使用的过程中查看netty源代码,方便开发。
方式二中netty被放入grpc-netty-shaded-1.26.0.jar的io.grpc.netty.shaded包中。这样的好处是当项目中有多个模块使用了不同版本的netty时,gRPC功能不会受到影响。但坏处就是不方便查看netty源代码了。
方式三与方式一相同,但不会引入像OkHttp这样与netty与gRPC不相关的jar。
总之,方式一和方式三都适合用在只需要使用单一netty版本的环境,方式二适合用在多个netty版本共存的环境 。
2、编写protobuf文件
在idea的插件市场下载安装protobuf的插件
创建src/main/proto/rpc_date.proto
1 | syntax = "proto3"; // 协议版本 |
使用maven插件进行编译
把target目录中生成的文件复制到java目录中
3、编写接口实现类
1 | // RPCDateServiceGrpc.RPCDateServiceImplBase 这个就是接口. |
4、定义服务端
1 | public class GRPCServer { |
5、定义客户端
1 | public class GRPCClient { |
使用Python搭建gRPC客户端
1、环境配置
protobuf 运行时(runtime)
1
pip install grpcio
安装 python 下的 protoc 编译器
1
pip install grpcio-tools
2、编译proto文件
1 | python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. rpc_date.proto |
3、编写客户端
1 | import grpc |
最后
proto文件中的包名也要保持一致,最好不要改动
原文链接: https://alexhuihui.github.io/article/20220210.html
版权声明: 转载请注明出处.