场景
gPRC简介以及Java中使用gPRC实现客户端与服务端通信(附代码下载):
在上面的博客中介绍了gRPC以及使用最基本的rpc通信方式即一个请求对象返回一个响应的方式进行通信。
除此之外gRPC还有以下三种方式。
服务端流式
一个请求对象,服务端返回多个结果对象
proto示例语法
rpc GetStudentsByAge(StudentRequest) returns (stream StudentResponse) {}
客户端流式
客户端传入多个请求对象,服务端返回一个响应结果。
proto示例语法
rpc GetStudentsWrapperByAges(stream StudentRequest) returns (StudentResponseList) {}
双向流式
传入多个对象可以返回多个响应对象
注:
实现
服务端流式实现
在上面博客的基础上,打开Person.proto文件
message StudentRequest {
int32 age= 1;
}
message StudentResponse {string name = 1;
int32 age= 2;string city = 3;
}
添加两个message作为请求和响应对象。
因为gRPC的请求和响应对象必须在message中定义,不能直接使用string或者int32这种作为参数。
然后在新建接口方法
service PersonService {
rpc GetStudentsByAge(StudentRequest) returns (stream StudentResponse) {}
}
此方法是要请求参数为一个age,然后返回多个学生对象。
然后调用插件生成代码。
然后来到PersonServiceImpl中对接口方法进行实现
@Overridepublic void getStudentsByAge(StudentRequest request, StreamObserverresponseObserver) {
System.out.println("接收到的客户端消息为:"+request.getAge());
responseObserver.onNext(StudentResponse.newBuilder().setName("1公众号:霸道的程序猿")
.setAge(30)
.setCity("北京")
.build());
responseObserver.onNext(StudentResponse.newBuilder().setName("2公众号:霸道的程序猿")
.setAge(40)
.setCity("上海")
.build());
responseObserver.onNext(StudentResponse.newBuilder().setName("3公众号:霸道的程序猿")
.setAge(50)
.setCity("广州")
.build());
responseObserver.onCompleted();
}
然后来到客户端中<