一、grpc的依赖
<dependencies><dependency><groupId>net.devh</groupId><artifactId>grpc-server-spring-boot-starter</artifactId><version>2.9.0.RELEASE</version></dependency></dependencies><build><extensions><extension><groupId>kr.motd.maven</groupId><artifactId>os-maven-plugin</artifactId><version>${os.plugin.version}</version></extension></extensions><plugins><plugin><groupId>org.xolstice.maven.plugins</groupId><artifactId>protobuf-maven-plugin</artifactId><version>${protobuf.plugin.version}</version><configuration><protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact><pluginId>grpc-java</pluginId><pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact></configuration><executions><execution><goals><goal>compile</goal><goal>compile-custom</goal></goals></execution></executions></plugin></plugins></build>
</project>
二、proto的编写
syntax = "proto3";option java_multiple_files = true;
option java_package = "com.ut.msfw1a.services.openapiservice.proto";//生成代码的位置service EventInfoService {rpc sendMessageEvent(EventInfoMessage) returns (EventInfoResponse) {}
}message EventInfoMessage {string commonInfo = 1;string flag =2;string data = 3;
}message EventInfoResponse {string msg = 1;
}
存放的位置和java同级
三、运行这两个插件
(如果出现报错,可能是因为电脑没有安装protobuf的命令,需要提前安装并配置环境变量)
四、生成的文件
生成的文件根据写的proto生成,可以把生成的文件挪到项目中,也可以就放在target
五、实现类的编写
@GrpcService
public class EventInfoServiceGrpcImpl extends EventInfoServiceGrpc.EventInfoServiceImplBase {@Overridepublic void sendMessageEvent(EventInfoMessage request, StreamObserver<EventInfoResponse> responseObserver) {EventInfoResponse.Builder eventInfo = EventInfoResponse.newBuilder();//业务处理String msg = request.getMsg();String msg = request.getCommonInfo();//if ("success".equals(msg)){eventInfo.setCode(200).setMsg("success"+100000).setSuccess(true);eventInfo.setMsg("success"+100000);}else{eventInfo.setCode(500).setMsg("error"+100000).setSuccess(false);eventInfo.setMsg("error"+100000);}responseObserver.onNext(eventInfo.build());
六、客户端调用测试(Python)
- 将proto文件放到本地的一个文件夹,然后执行
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. pb.proto
- 会生成下面的文件
3. 编写测试脚本
import grpc
import pb_pb2 # 从生成的 proto 文件中导入生成的类
import pb_pb2_grpc # 从生成的 proto 文件中导入生成的服务def run():channel = grpc.insecure_channel('localhost:7778') # 连接到 gRPC 服务器stub = pb_pb2_grpc.EventInfoServiceStub(channel)# 创建消息pb_message = pb_pb2.EventInfoMessage()pb_message.msg = "success"# 调用服务方法response = stub.sendMessageEvent(pb_message)print("Response received:")print("Code:", response.code)print("Message:", response.msg)print("Success:", response.success)if __name__ == '__main__':run()
- 运行
python test_grpc.py
- 成功返回结果