netty学习笔记10-grpc入门

需求:使用grpc完成一个最简单的rpc的调用

1. 编写proto文件(该文件需要放到src/main/proto目录下)

syntax = "proto3";
package com.baidu.grpc;
option java_package = "com.baidu.grpc";
option java_outer_classname = "PersonData";
option java_multiple_files = true;

message PersonRequest{
    int32 id = 1;
}
message PersonResponse{
    int32 id = 1;
    string name = 2;
}

service PersonService{
    rpc getPersonById(PersonRequest) returns (PersonResponse);
}

2. 使用grpc的插件完成代码的生成

    gradle generateProto 

3. 实现对于的接口

package com.baidu.grpc;

public class PersonServiceImpl extends PersonServiceGrpc.PersonServiceImplBase {

    public void getPersonById(com.baidu.grpc.PersonRequest request,
                              io.grpc.stub.StreamObserver responseObserver) {
        Integer id = request.getId();
        System.out.println("id:" + id);
        responseObserver.onNext(PersonResponse.newBuilder().setId(1).setName("admin").build());
        responseObserver.onCompleted();
    }
}

4. 编写服务器端

package com.baidu.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;

public class GrpcServer {
    private Server server;

    public void start() throws Exception{
        server = ServerBuilder.forPort(8899).addService(new PersonServiceImpl()).build().start();
        System.out.println("服务器启动成功");
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                if (null != server)
                {
                    System.out.println("jvm关闭");
                    GrpcServer.this.server.shutdown();
                }
            }
        });
    }

    public void stop() {
        if (null != server){
            server.shutdown();
        }
    }

    public void awaitTermination() throws Exception{
        if (null != server) {
            server.awaitTermination();
        }
    }

    public static void main(String[] args) throws Exception {
        GrpcServer grpcServer = new GrpcServer();
        grpcServer.start();
        grpcServer.awaitTermination();
    }
}

5. 编写客户端

package com.baidu.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class GrpcClient {
    public static void main(String[] args) {
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost",8899).usePlaintext(true).build();
        PersonServiceGrpc.PersonServiceBlockingStub personServiceBlockingStub =  PersonServiceGrpc.newBlockingStub(managedChannel);
        PersonResponse response = personServiceBlockingStub.getPersonById(PersonRequest.newBuilder().setId(1).build());
        System.out.println(response.getId() + " : " + response.getName());
    }
}

你可能感兴趣的:(netty自学笔记)