SpringBoot整合gRPC - proto3 -- 简单明了

  1. 项目结构
    在这里插入图片描述

  2. pom引入(parent中引入即可)

    <properties>
        <net-devh-grpc.version>2.14.0.RELEASE</net-devh-grpc.version>
        <os-maven-plugin.version>1.6.0</os-maven-plugin.version>
        <protobuf-maven-plugin.version>0.5.1</protobuf-maven-plugin.version>
    </properties>
    
    <dependency>
        <groupId>net.devh</groupId>
        <artifactId>grpc-spring-boot-starter</artifactId>
        <version>2.14.0.RELEASE</version>
    </dependency>
    
  3. 创建lib、service、client服务
    a. lib中, 创建proto文件
    在这里插入图片描述

    syntax = "proto3";
    option java_package = "com.mose.proto.msg";
    
    // 定义service -- 即 class
    service MsgService {
      // 定义 方法名   入参对象     返回      回参对象
      rpc SendMsg (MsgRequest) returns (MsgResponse);
    }
    
    // 定义 入参对象
    // 其中的 1、2、3 只是为了排序
    message MsgRequest {
      int32 a = 1;
      int32 b = 2;
      Type type = 3;
    }
    
    // 定义 回参对象
    message MsgResponse {
      int32 c = 1;
    }
    
    // 定义 入参/回参 枚举类型
    // 默认值为第一个,即 = 0 的为默认值
    enum Type {
      add = 0;
      cut = 1;
    }
    

b. pom中增加build信息

 <build>
     <extensions>
         <!-- os-maven-plugin -->
         <extension>
             <groupId>kr.motd.maven</groupId>
             <artifactId>os-maven-plugin</artifactId>
             <version>${os-maven-plugin.version}</version>
         </extension>
     </extensions>
     <plugins>
         <plugin>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
             <executions>
                 <execution>
                     <goals>
                         <goal>repackage</goal>
                     </goals>
                 </execution>
             </executions>
         </plugin>
         <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-surefire-plugin</artifactId>
             <configuration>
                 <skip>true</skip>
             </configuration>
         </plugin>
         <!-- protobuf-maven-plugin -->
         <plugin>
             <groupId>org.xolstice.maven.plugins</groupId>
             <artifactId>protobuf-maven-plugin</artifactId>
             <version>${protobuf-maven-plugin.version}</version>
             <configuration>
                 <protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
                 <pluginId>grpc-java</pluginId>
                 <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.11.0:exe:${os.detected.classifier}</pluginArtifact>
                 <outputDirectory>${project.build.sourceDirectory}</outputDirectory>
                 <clearOutputDirectory>false</clearOutputDirectory>
             </configuration>
             <executions>
                 <execution>
                     <goals>
                         <goal>compile</goal>
                         <goal>compile-custom</goal>
                     </goals>
                 </execution>
             </executions>
         </plugin>
     </plugins>
 </build>

c. 在lib中执行 mvn clean install , 即可生成proto文件对应的java文件,如下图
在这里插入图片描述

  1. service 实现接口

    server:
      port: 8081
    spring:
      application:
        name: grpc-service
    grpc:
      server:
        port: 9091
    
    import com.mose.proto.msg.Msg;
    import com.mose.proto.msg.MsgServiceGrpc;
    import io.grpc.stub.StreamObserver;
    import net.devh.boot.grpc.server.service.GrpcService;
    
    @GrpcService
    public class MsgService extends MsgServiceGrpc.MsgServiceImplBase {
        @Override
        public void sendMsg(Msg.MsgRequest request, StreamObserver<Msg.MsgResponse> responseObserver) {
            // 获取参数
            int a = request.getA();
            int b = request.getB();
            Msg.Type type = request.getType();
    
            // 处理逻辑
            int c = 0;
    
            switch (type) {
                case add:
                    c = a + b;
                    break;
                case cut:
                    c = a - b;
                    break;
            }
    
            // 构造回参
            Msg.MsgResponse response = Msg.MsgResponse.newBuilder().setC(c).build();
    
            // 返回
            responseObserver.onNext(response);
    
            // 处理完成
            responseObserver.onCompleted();
        }
    }
    
  2. client 调用接口

    server:
      port: 8082
    spring:
      application:
        name: grpc-client
    grpc:
      server:
        port: 9092
      client:
        grpc-service:
          address: localhost:9091
          negotiation-type: plaintext
    
    import com.mose.proto.msg.Msg;
    import com.mose.proto.msg.MsgServiceGrpc;
    import net.devh.boot.grpc.client.inject.GrpcClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MsgController {
    
        /**
         * 获取调用存根
         */
        @GrpcClient("grpc-service")
        private MsgServiceGrpc.MsgServiceBlockingStub stub;
    
        @GetMapping("msg")
        public int sendMsg(int a, int b) {
            return stub.sendMsg(
                            // 构造入参
                            Msg.MsgRequest.newBuilder().setA(a).setB(b).setType(Msg.Type.cut).build()
                    )
                    // 获取回参
                    .getC();
        }
    }
    
    
  3. 调用 以及结果
    在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Spring Boot整合gRPC,可以按照以下步骤进行操作: 1. 首先,在pom.xml文件中添加gRPCprotobuf的依赖。例如: ```xml <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty-shaded</artifactId> <version>1.40.1</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>1.40.1</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>1.40.1</version> </dependency> ``` 2. 定义一个gRPC服务,使用Protocol Buffers(protobuf)编写服务定义。例如,创建一个名为`HelloWorld.proto`的文件,定义一个简单的HelloWorld服务: ```protobuf syntax = "proto3"; package com.example.grpc; service HelloWorldService { rpc sayHello (HelloRequest) returns (HelloResponse); } message HelloRequest { string name = 1; } message HelloResponse { string message = 1; } ``` 3. 使用protobuf插件生成Java类文件。可以通过在pom.xml中配置protobuf插件来实现。例如: ```xml <build> <plugins> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.6.1</version> <configuration> <protocArtifact>com.google.protobuf:protoc:3.17.3:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.40.1:exe:${os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` 运行`mvn clean install`命令,将会生成Java类文件。 4. 创建实现gRPC服务的类。例如,创建一个名为`HelloWorldServiceImpl`的类,实现HelloWorldService: ```java import io.grpc.stub.StreamObserver; import com.example.grpc.HelloRequest; import com.example.grpc.HelloResponse; import com.example.grpc.HelloWorldServiceGrpc; public class HelloWorldServiceImpl extends HelloWorldServiceGrpc.HelloWorldServiceImplBase { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { String message = "Hello, " + request.getName() + "!"; HelloResponse response = HelloResponse.newBuilder().setMessage(message).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } ``` 5. 在Spring Boot应用程序中配置gRPC服务。例如,创建一个名为`GrpcServerConfiguration`的类,配置gRPC服务器: ```java import org.lognet.springboot.grpc.GRpcService; import com.example.grpc.HelloWorldServiceGrpc; @Configuration public class GrpcServerConfiguration { @Bean public Server grpcServer() { return ServerBuilder.forPort(9090).addService(new HelloWorldServiceImpl()).build(); } @GRpcService public HelloWorldServiceGrpc.HelloWorldServiceImplBase helloWorldService() { return new HelloWorldServiceImpl(); } } ``` 6. 启动Spring Boot应用程序,并在9090端口上监听gRPC请求。你可以使用gRPC客户端与服务进行通信了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mose-x

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值