grpc整合Springboot

本文介绍了如何在SpringBoot项目中集成gRPC和protobuf,包括添加依赖、编写proto文件、运行编译插件、生成Java服务实现以及Python客户端的调用测试。

一、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 {

    @Override
    public 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)

  1. 将proto文件放到本地的一个文件夹,然后执行python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. pb.proto
  2. 会生成下面的文件

在这里插入图片描述
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()
  1. 运行python test_grpc.py
  2. 成功返回结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值