一.通过maven导入所需jar包
<!--grpc服务-->
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.28.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.28.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.28.0</version>
</dependency>
二.定义proto文件
实例:
syntax = "proto3";
package com.csdn;
option java_multiple_files = true;
message GrpcRequest {
string msg=1;
}
message GrpcResponse {
string returninfo = 1;
}
service grpcService {
rpc greet(GrpcRequest) returns (GrpcResponse);
}
相关语法:gRPC之proto语法 - 简书
三.根据proto生成代码,这里介绍两种方式
第一种利用idea的protobuf插件来生成代码,配置如下:
<!--Probuff工具-->
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<!--suppress UnresolvedMavenProperty -->
<protocArtifact>com.google.protobuf:protoc:3.12.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<!--suppress UnresolvedMavenProperty -->
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.30.2:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
</plugin>
此处注意,mac m1芯片执行会报错 ,因为protobuf暂不支持m1芯片,推荐两种解决方案:
1.将os.detected.classifier设置为x86的结构
<properties>
<os.detected.classifier>osx-x86_64</os.detected.classifier>
</properties>
注意查看自己的本地仓库,是否获取到正确的版本
我在测试时,就未获取到这个文件,导致生成不了service代码,只能手动下载后使用指令去生成代码
2.去github上获取源码,重新编译,具体操作详见:Mac M1(Apple Silicon) 安装 protobuf 2.5.0 - 简书
第二种是自己下载对应的jar包,通过命令手动生成,具体操作如下:
参考文章:protobuf java service_【java】protoc不生成.proto中的service,只生成model相关类,求助。..._weixin_39807954的博客-CSDN博客
mac环境下无法直接调用exe文件,需要自己获取源码编译
四.服务端代码
五.客户端代码