Welcome everyone

spring boot 集成 grpc

java 汪明鑫 812浏览 0评论

grpc就和其他一些rpc框架差不多

支持多语言的 RPC 框架,是由 Google 开发并开源的一种语言中立的 RPC 框架

基于HTTP/2协议设计

 

 

grpc 是用proto文件定义rpc服务

protobuf全名是ProtocolBuffers,是谷歌推出的二进制序列化协议,提供IDL文件来定义各种类型的数据。

目前整体协议版本是proto3,protobuf提供了从proto文件编译生成各个语言文件的功能。

 

pom.xml 引入proto文件编译配置

<build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId><!--引入操作系统os设置的属性插件,否则${os.detected.classifier} 操作系统版本会找不到 -->
                <version>1.5.0.Final</version>
            </extension>
        </extensions>
        <plugins>
            <!--添加编译proto文件的编译程序和对应的编译插件-->
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.1</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.14.0:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

 

定义我们的proto文件,文件后缀是.proto

 

syntax = "proto3";//请在非空非注释的第一行指定当前文件使用的是proto3的语法,默认proto2

package grpc;//package与java_package有些不同,java_package是定义编译生成的java文件所在的目录,而package是对应的java类的命名空间
option java_package = "pers.wxm.grpc.core";
option java_outer_classname = "HelloWorldServiceProto";//要生成Java类的名称
option java_multiple_files = true;//编译后会生成多个Message类,并没有被包含在HelloWorldServiceProto.java文件中,反之,生成单一HelloWorldServiceProto.java文件

//服务端接口类
service HelloWorldRpc {
    rpc SayHello (HelloRequest) returns (HelloResponse) {} //服务端接口方法
}

//请求参数 基于序号的协议字段映射
message HelloRequest {
    string name = 1;
    string sex = 2;
}

//响应参数
message HelloResponse {
    string message = 1;
}

 

编译一下

protobuf:compile  //编译消息对象
protobuf:compile-custom  //依赖消息对象,生成接口服务

 

生成对应的Java代码

 

引入grpc starter

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

 

点进去,里面主要是spring boot,grpc,protobuf的核心依赖

<dependencies>
    <dependency>
      <groupId>net.devh</groupId>
      <artifactId>grpc-common-spring-boot</artifactId>
      <version>2.2.0.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.0.6.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-netty</artifactId>
      <version>1.17.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-protobuf</artifactId>
      <version>1.17.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-stub</artifactId>
      <version>1.17.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-services</artifactId>
      <version>1.17.1</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

 

编写rpc服务实现

package pers.wmx.xinye;

import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import pers.wxm.grpc.core.HelloRequest;
import pers.wxm.grpc.core.HelloResponse;
import pers.wxm.grpc.core.HelloWorldRpcGrpc.HelloWorldRpcImplBase;

/**
 * Grpc 服务端
 *
 * @author: wangmingxin03
 * @date: 2020-06-10
 */
@GrpcService
public class HelloService extends HelloWorldRpcImplBase {

    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        String sayHello = "hello " + request.getName();
        HelloResponse response = HelloResponse
                .newBuilder().setMessage(sayHello).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

}

 

定义端口号

 

 

跑一波单测

package pers.wmx.xinye;

import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import pers.wxm.grpc.core.HelloRequest;
import pers.wxm.grpc.core.HelloResponse;
import pers.wxm.grpc.core.HelloWorldRpcGrpc;

/**
 * @author: wangmingxin03
 * @date: 2020-06-10
 */
@SpringBootTest
public class GrpcServiceClientTest {

    private ManagedChannel channel;
    private HelloWorldRpcGrpc.HelloWorldRpcBlockingStub helloWorldBlockingStub;

    @Test
    public void test () {
        channel = ManagedChannelBuilder.forAddress("127.0.0.1", 9099)
                .usePlaintext()
                .build();

        helloWorldBlockingStub = HelloWorldRpcGrpc.newBlockingStub(channel);

        HelloResponse response = helloWorldBlockingStub.sayHello(convertRequest("张三","man"));
        System.out.println(response.getMessage());
    }

    private HelloRequest convertRequest (String name, String sex) {
        HelloRequest helloRequest = HelloRequest.newBuilder()
                .setName(name)
                .setSex(sex)
                .build();
        return helloRequest;
    }

    public void shutdown() {
        try {
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

 

整体目录结构

 

 

转载请注明:汪明鑫的个人博客 » spring boot 集成 grpc

喜欢 (0)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz