grpc-server服务端实现
首先,准备grpc-samples工程,pom文件中添加grpc-spring-boot-starter依赖
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-spring-boot-starter</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
然后,以上篇文章 maven插件编译proto文件 生成的客户端服务端代码为例,实现GreeterGrpc.GreeterImplBase接口服务sayHello,下面是接口服务的逻辑实现
@Slf4j
@GrpcService
public class GrpcServerService extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
log.info("接收到 GRPC-Client 消息:{}",req.getName());
HelloReply reply = HelloReply.newBuilder().setMessage("Hello =============> " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
接下来在application.yml配置服务端口
#grpc相关配置
grpc:
server:
port: 9099 #默认端口9090
grpc-client客户端实现
@Slf4j
public class GrpcServiceClientTest {
private ManagedChannel channel;
private GreeterGrpc.GreeterBlockingStub greeterBlockingStub;
@Test
public void test () {
try {
HelloReply reply = greeterBlockingStub.sayHello(convertRequest("张三","man"));
log.info("接收到服务端返回结果:{}",reply.toString());
} finally {
shutdown();
}
}
@Before
public void init () {
log.info(" grpc-client connect start.");
channel = ManagedChannelBuilder.forAddress("127.0.0.1", 9099)
.usePlaintext()
.build();//池化处理 成本高
greeterBlockingStub = GreeterGrpc.newBlockingStub(channel);
}
public void shutdown() {
try {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private HelloRequest convertRequest (String name, String sex) {
HelloRequest helloRequest = HelloRequest.newBuilder()
.setName(name)
.setSex(sex)
.build();
return helloRequest;
}
好了,就这么简单,启动grpc服务端,我们可以让grpc client 和server完成通信了!
网友评论