Grpc java 踩坑

Server端:

import a.b.c.*;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import other.person;
public class Gepc extends TestServerGrpc.TestServerImplBase {
    
    
    @Override
    public void test(TestMessage request, StreamObserver<TestMessage> responseObserver)  {
    
    
        int age = request.getTest().getAge();
        String name = request.getTest().getName();
        String message = message(age,name);
        responseObserver.onNext(TestMessage.newBuilder()
                .setTest(person.newBuilder().setAge(age).setName(name).build())
                .setMessage(message)
                .build());
        responseObserver.onCompleted();
    }
    public String message(int age,String name){
    
    
        return "你的年龄是"+age+"你的名字是"+name;
    }
    public static void main(String[] args) throws Exception {
    
    
        ServerBuilder.forPort(9999)
                .addService(new Gepc())
                .build().start();
        System.out.println("Server端启动了");
        while(true){
    
    
        }
    }
}

Client端:

import a.b.c.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import other.person;

public class GrpcClient {
    
    
    ManagedChannel channel;
    TestServerGrpc.TestServerBlockingStub stub;
    public static void main(String[] args) {
    
    
        GrpcClient client = new GrpcClient();
        TestMessage testMessage = client.stub.test(
                TestMessage
                .newBuilder()
                .setTest(person.newBuilder().setName("神明").setAge(89).build())
                        .build());
        System.out.println(testMessage.getTest());
        System.out.println(testMessage.getMessage());
    }
    public GrpcClient(){
    
    
         channel = ManagedChannelBuilder
                 .forAddress("127.0.0.1",9999)
                 .usePlaintext()
                 .build();
         stub = TestServerGrpc.newBlockingStub(channel);
    }
}

proto文件(add.proto):

syntax = "proto3";
import "otherproto.proto";
package mygrpc;
option java_package = "a.b.c";
option java_outer_classname = "AddServiceProto";
option java_multiple_files = true;
service TestServer{
    
    
    rpc test(TestMessage) returns (TestMessage){
    
    };
}
message TestMessage{
    
    
    otherproto.person test = 1;
    string message = 2;
}

proto文件(otherproto.proto):

syntax = "proto3";
package otherproto;
option java_package="other";
option java_outer_classname="otherclass";
option java_multiple_files = true;
message person{
  int32 age = 1;
  string name = 2;
}

坑:
在这里插入图片描述
在一个proto文件去调用另一个文件的时候,生成的代码会报错。
在这里插入图片描述
当执行Server端的时候会报这个错。
解决办法:
在这里插入图片描述
把这个other. 删除之后就可以正常启动了
在这里插入图片描述
在导入其他文件会报错:
在这里插入图片描述
把这个在设置里添加自己的目录就好了

猜你喜欢

转载自blog.csdn.net/weixin_43170526/article/details/113593591