服务端
@Component
public class Greeter extends GreeterGrpc.GreeterImplBase implements InitializingBean {
//streamObserver 一个应答的观察者
@Override
public void sayHello(Helloworld.HelloRequest request,
io.grpc.stub.StreamObserver<Helloworld.HelloReply> responseObserver) {
Helloworld.HelloReply helloReply = Helloworld.HelloReply.newBuilder().setMessage("hello world").build();
//添加返回值,完成调用
responseObserver.onNext(helloReply);//添加返回值
responseObserver.onCompleted();//完成调用
}
@Override
public void afterPropertiesSet() throws Exception {
int port = 9098;
ServerBuilder.forPort(port)
.addService(new Greeter())
.build()
.start();
System.out.println("server port:"+port);
}
}
* 继承GreeterGrpc.GreeterImplBase重写里面的sayHello方法;GreeterGrpc.GreeterImplBase就是我们在proto文件中定义的服务
* ServerBuilder的forPort方法用来指定一个端口,用addService来添加一个服务类,也就是当前类
* grpc生成的消息类有点独特,他们没有set方法,只有get方法,想要賦值,要用他们的一个内部类Builder来间接賦值
* Helloworld.HelloReply helloReply = Helloworld.HelloReply.newBuilder().setMessage("liuwenhui").build();
客户端
@RunWith(SpringRunner.class)
@SpringBootTest
public class GrpcApplicationTests {
@Autowired
private JavaGrpcClient javaGrpcClient;
@Test
public void contextLoads() {
/*Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName("lwh").build();
Helloworld.HelloReply helloReply = javaGrpcClient.run(o->o.sayHello(request));
System.out.println(helloReply.getMessage());*/
Channel channel = ManagedChannelBuilder
.forAddress("127.0.0.1", 9098)//服务端
.usePlaintext(true)//usePlaintext的意思是使用明文不加密(应该可以加密)
.build();
//创建阻塞的/同步存根 blockingStub
GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel);
Helloworld.HelloRequest request = Helloworld.HelloRequest.newBuilder().setName("lwh").build();
//调用服务器方法
Helloworld.HelloReply helloReply = blockingStub.sayHello(request);
System.out.println(helloReply.getMessage());
}
}