什么是gRPC
gRPC 是Google发起的一个开源远程过程调用 系统。该系统基于HTTP/2 协议传输,使用Protocol Buffers 作为接口描述语言。 其他功能: 认证 双向流 流控制 过期 最常见的应用场景是: 微服务框架下,多种语言服务之间的高效交互。 将手机服务、浏览器连接至后台 产生高效的客户端库。
简单来说就是,基于Protocol Buffers通信协议的RPC框架
支持的客户端语言
Android
C#
C++
Dart
Go
Java
Objective-C
PHP
Python
Ruby
Web
下面进入正题
我们将使用以下框架 or 工具(我是一个喜新厌旧的人)
IDEA 2019.3
Gradle 6.0.1
Spring Boot 2.2.2
gRPC 1.26.0
protobuf 3.11.2
build.gradle文件如下
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'com.google.protobuf' version '0.8.11'
id 'java'
id 'idea'
}
group = 'example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
maven{ url 'https://maven.aliyun.com/repository/public'}
mavenCentral()
}
def grpcVersion = '1.26.0' // CURRENT_GRPC_VERSION
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation "io.grpc:grpc-protobuf:${grpcVersion}"
implementation "io.grpc:grpc-stub:${grpcVersion}"
implementation "io.grpc:grpc-netty:${grpcVersion}"
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
protobuf {
protoc { artifact = "com.google.protobuf:protoc:3.11.2" }
plugins {
grpc { artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}" }
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}
// Inform IDEs like IntelliJ IDEA, Eclipse or NetBeans about the generated code.
sourceSets {
main {
java {
srcDirs 'build/generated/source/proto/main/grpc'
srcDirs 'build/generated/source/proto/main/java'
}
}
}
创建Protocol Buffers定义服务文件
在src/main目录下创建proto目录,然后在里面创建HelloService.proto文件编写如下内容;
syntax="proto3";
option java_multiple_files = true;
package example.grpc;
message HelloRequest {
string firstName = 1;
string lastName = 2;
}
message HelloResponse {
string greeting = 1;
}
service HelloService {
rpc hello(HelloRequest) returns (HelloResponse);
}
根据定义文件让gradle自动生成依赖文件
gradle generateProto
创建服务端gRPC Service
用于处理请求并返回,就像我们spring controller接收的GetMapping请求一样
创建文件
src/main/example/grcp/service/HelloServiceImpl.java
package example.grpc.service;
import example.grpc.*;
import io.grpc.stub.StreamObserver;
public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void hello(
HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
System.out.println("Request received from client:\n" + request);
String greeting = new StringBuilder().append("Hello, ")
.append(request.getFirstName())
.append(" ")
.append(request.getLastName())
.toString();
HelloResponse response = HelloResponse.newBuilder()
.setGreeting(greeting)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
利用Spring的启动器来启动gRPC服务端
用于给我们的客户端提供服务开启gRPC服务
创建文件
src/main/java/example/GrpcServerStartupRunner.java
package example.grpc;
import example.grpc.service.HelloServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.util.TransmitStatusRuntimeExceptionInterceptor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class GrpcServerStartupRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
ServerBuilder serverBuilder = ServerBuilder
.forPort(8081)
.addService(new HelloServiceImpl());
Server server = serverBuilder.build();
serverBuilder.intercept(TransmitStatusRuntimeExceptionInterceptor.instance());
server.start();
startDaemonAwaitThread(server);
}
private void startDaemonAwaitThread(Server server) {
Thread awaitThread = new Thread(() -> {
try {
server.awaitTermination();
} catch (InterruptedException ignore) {
}
});
awaitThread.setDaemon(false);
awaitThread.start();
}
}
至此服务端相关代码完毕,下面来搞定客户端
客户端代码就很简单了
我们直接在Spring Boot的Appliction文件里创建个get请求来调用gRPC的服务
src/main/java/example/grpc/ExampleGrpcApplication.java
package example.grpc;
import com.google.common.base.Stopwatch;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class ExampleGrpcApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleGrpcApplication.class, args);
}
@GetMapping("/")
public ResponseEntity test() {
ManagedChannel channel = ManagedChannelBuilder.forAddress("127.0.0.1", 8081)
.usePlaintext()
.build();
Stopwatch stopwatch = Stopwatch.createStarted();
HelloServiceGrpc.HelloServiceBlockingStub stub
= HelloServiceGrpc.newBlockingStub(channel);
HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder()
.setFirstName("Ga0x")
.setLastName("gRPC")
.build());
System.out.println(stopwatch.stop());
System.out.println("Response received from server:\n" + helloResponse);
channel.shutdown();
return ResponseEntity.ok(helloResponse.getGreeting());
}
}
返回Hello, Baeldung gRPC
后台console log
Request received from client:
firstName: "Ga0x"
lastName: "gRPC"
8.780 ms
Response received from server:
greeting: "Hello, Ga0x gRPC"