SpringBoot集成gRPC的步驟如下:
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.41.0</version>
</dependency>
syntax = "proto3";
package com.example;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
@GrpcService
public class GreeterService extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
String message = "Hello " + request.getName();
HelloReply reply = HelloReply.newBuilder().setMessage(message).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
@Configuration
public class GrpcConfig {
@Bean
public Server grpcServer(List<BindableService> services) {
ServerBuilder<?> serverBuilder = ServerBuilder.forPort(9090);
services.forEach(serverBuilder::addService);
return serverBuilder.build();
}
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
public class GrpcClient {
public static void main(String[] args) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090)
.usePlaintext()
.build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloReply reply = stub.sayHello(HelloRequest.newBuilder().setName("World").build());
System.out.println(reply.getMessage());
channel.shutdown();
}
}
通過以上步驟,就可以完成SpringBoot集成gRPC的開發工作。