Springboot integrates GRPC

Springboot integrates GRPC

Springboot integrates GRPC, the following preparations need to be made

    1. server side
    1. client side
    1. proto file
    1. corresponding pom

Step 1. Create java maven project

Use maven to manage the Jar package, the project directory is as follows:
insert image description here

Step 2. Add the corresponding dependencies in pom.xml,

Pay attention to the version of dependencies, the code generated by different versions may not be the same, because it is a sample demo, so I put the two corresponding packages in the outermost pom, in the real project, both should be separated in different In the project, achieve the minimum dependency; the imported POM is not the only method, you can also import the sprintboot pom separately, and then import the grpc-related ones, these methods are all possible, but this package integrates these, which is more convenient to use , online projects can be determined according to the situation.

client pom

<dependency>
    <groupId>net.devh</groupId>
    <artifactId>grpc-client-spring-boot-starter</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>

server pom

<dependency>
    <groupId>net.devh</groupId>
    <artifactId>grpc-server-spring-boot-starter</artifactId>
    <version>2.6.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-stub</artifactId>
    <version>1.29.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-protobuf</artifactId>
    <version>1.29.0</version>
</dependency>

Step 3. Write proto file

Need to pay attention to the location of the file storage.

syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.sunrj.grpc.userInfo";

service UserInfoService {
    
    
  rpc queryUserInfo(UserInfoReq) returns (UserInfoResponse) {
    
    }
  rpc queryUserInfo2(UserInfoReq) returns (UserInfoResponse) {
    
    }
  rpc queryUserInfo3(UserStr) returns (UserStr) {
    
    }
}

message UserStr{
    
    
  string str = 1;
}


message UserInfoReq {
    
    
  string name = 1;
  int64 id = 2;
}
message UserInfoResponse {
    
    
  int32 code = 1;
  string msg = 2;
  bool success = 3;
  message Data {
    
    
    UserInfo userInfo = 1;
  }
  Data data = 4;
}
message UserInfo {
    
    
  int64 id = 1;
  string name = 2;
  string sex = 3;
  string addr = 4;
}

insert image description here

Step 4. Add compilation dependencies in pom.xml of api

Here you need to pay attention to the version (protoc:3.12.0)

<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.6.2</version>
        </extension>
    </extensions>
    <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.0.0:exe:${os.detected.classifier}</protocArtifact>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.0:exe:${os.detected.classifier}</pluginArtifact>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Step 5. Generate GRPC code

In idea, use ideal, and click compile directly in the maven operation area. If an error occurs, you may need to install the protobuf plug-in. After clicking compile, the code will be generated in the corresponding directory. The directory setting is based on step 4 and the proto setting Decide.
insert image description here

The generated directory is as follows

insert image description here

Step 6. To write the server-side code, you need to introduce the pom of the api

Directory structure on the server side
insert image description here

Step 6.1 application.yaml

server:
  port: 8081

spring:
  application:
    name: server

grpc:
  server:
    port: 8090

grpc.server.port refers to the grpc communication port
. spring.application.name refers to the project name of the server. The service name needs to be specified when the client accesses.
server.port refers to the port where the project starts

Step 6.2. Write startup class, standard startup class

@SpringBootApplication
public class GrpcServerApplication {
    
    

   public static void main(String[] args) {
    
    
      SpringApplication.run(GrpcServerApplication.class, args);
   }
}

Step 6.3 Write the receiving processing method, UserInfoServiceGrpcImpl,

It is used to process and receive client-side GRPC requests; this class directly inherits UserInfoServiceGrpc.UserInfoServiceImplBase and implements its methods. Since it is a springboot project, the class is managed by spring, so specific annotations need to be added

@GrpcService
package come.koal.service;
 
import com.sunrj.grpc.userInfo.*;
import net.devh.boot.grpc.server.service.GrpcService;


@GrpcService
public class UserInfoServiceGrpcImpl extends UserInfoServiceGrpc.UserInfoServiceImplBase {
    
    
    @Override
    public void queryUserInfo(UserInfoReq request, io.grpc.stub.StreamObserver<UserInfoResponse> responseObserver) {
    
    
        UserInfoResponse.Builder userInfoResp = UserInfoResponse.newBuilder();
        userInfoResp.setCode(0).setMsg("success").setSuccess(true);
        UserInfo.Builder userInfo = UserInfo.newBuilder();
        userInfo.setId(request.getId());
        userInfo.setName(request.getName());
 
        userInfoResp.setData(UserInfoResponse.Data.newBuilder().setUserInfo(userInfo));
        responseObserver.onNext(userInfoResp.build());
        responseObserver.onCompleted();
    }
 
    @Override
    public void queryUserInfo2(UserInfoReq request, io.grpc.stub.StreamObserver<UserInfoResponse> responseObserver) {
    
    
        super.queryUserInfo2(request, responseObserver);
    }
 
    @Override
    public void queryUserInfo3(UserStr request, io.grpc.stub.StreamObserver<UserStr> responseObserver) {
    
    
        System.out.println("queryUserInfo3 =======> " + request.getStr());
        responseObserver.onNext(UserStr.newBuilder().setStr("msg : success").build());
        responseObserver.onCompleted();
    }
}

Step 7 To write the client-side code, you need to introduce the pom of the api

The directory structure of the client
insert image description here

Write application.yml

server:
  port: 8891

spring:
  application:
    name: client


grpc:
  client:
    grpc-server:
      address: static://localhost:8090
      enableKeepAlive: true
      keepAliveWithoutCalls: true
      negotiationType: plaintext

grpc.client.grpc-server needs to configure the information of the server to be built

startup class

@SpringBootApplication
public class GrpcClientApplication {
    
    

   public static void main(String[] args) {
    
    
      SpringApplication.run(GrpcClientApplication.class, args);
   }
}

Write Controller,

This controller is the controller of the rest request, called by url, which is
the value in this @GrpcClient, which is the name of the server (spring.application.name)

package com.koal.controller;


import com.sunrj.grpc.userInfo.UserInfoServiceGrpc;
import com.sunrj.grpc.userInfo.UserStr;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.concurrent.ExecutionException;
 
 
 
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    
    
 
    @GrpcClient("grpc-server")
    UserInfoServiceGrpc.UserInfoServiceFutureStub userInfoServiceStub;
 
 
    @RequestMapping(value="/query/{id}")
    public String queryUser(@PathVariable Integer id, String str)  {
    
    
        String userResp = null;
        try {
    
    
 
            userResp = userInfoServiceStub.queryUserInfo3(UserStr.newBuilder().setStr(str).build()).get().getStr();
            return userResp;
        } catch (InterruptedException e) {
    
    
 
        } catch (ExecutionException e) {
    
    
 
        }
        return userResp;
    }
 
}

test

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/sunrj_niu/article/details/127402842