Server side:
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 side:
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 file (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 file (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;
}
Pit:
When a proto file calls another file, the generated code will report an error.
This error will be reported when the Server side is executed.
Solution:
After deleting this other., it can start normally.
When importing other files, an error will be reported:
just add this to the settings and add your own directory.