一、流式RPC的三种具体形式
流式RPC不同于简单RPC只有“单发单收“一种形式,而是可以分为三种不同的形式——“应答流式RPC”,“请求流式RPC”,“双向流式RPC”。对于这三种不同的形式,python有不同的请求及接收方式,下面就让我们来具体了解一下。(对于下面操作有疑问的同学可以去看上一期的内容)
首先接口协议是有区别的,我们来看三种形式的接口定义:
应答流式RPC:
rpc ListFeatures(Rectangle) returns (stream Feature) {}
请求流式RPC:
rpc RecordRoute(stream Point) returns (RouteSummary) {}
双向流式RPC:
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
可以看到,请求和响应参数中流式内容的前面会有一个stream标识,代表这是一个流式的内容。应答流式RPC只有返回是流式的,请求流式RPC只有请求是流式的,而双向流式RPC请求和返回都是流式的。
一个包含接口的完整proto协议文件(route_guide.proto)内容如下:
syntax = "proto3";option java_multiple_files = true;option java_package = "io.grpc.examples.routeguide";option java_outer_classname = "RouteGuideProto";option objc_class_prefix = "RTG";package routeguide;service RouteGuide {rpc ListFeatures(Rectangle) returns (stream Feature) {}rpc RecordRoute(stream Point) returns (RouteSummary) {}rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}}message Point {int32 latitude = 1;int32 longitude = 2;}message Rectangle {Point lo = 1;Point hi = 2;}message Feature {string name = 1;Point location = 2;}message RouteNote {Point location = 1;string message = 2;}message RouteSummary {int32 point_count = 1;int32 feature_count = 2;int32 distance = 3;int32 elapsed_time = 4;}
根据协议文件生成route_guide_pb2.py、route_guide_pb2_grpc.py两个必要的模块文件,然后就可以根据他们来创建客户端了。
二、客户端实现
1、应答流式RPC
应答流式RPC返回的内容为流式,一次请求,n次返回。我们可以用for循环来接收返回的内容:
def guide_list_features(stub):rectangle = route_guide_pb2.Rectangle(lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))print("Looking for features between 40, -75 and 42, -73")features = stub.ListFeatures(rectangle)for feature in features:print("Feature called %s at %s" % (feature.name, feature.location))
2、请求流式RPC
请求流式RPC请求的内容为流式,n次请求,一次返回。我们可以用迭代器来发送若干份请求数据:
def generate_route(feature_list):for _ in range(0, 10):random_feature = feature_list[random.randint(0, len(feature_list) - 1)]print("Visiting point %s" % random_feature.location)yield random_feature.locationdef guide_record_route(stub):feature_list = route_guide_resources.read_route_guide_database()route_iterator = generate_route(feature_list)route_summary = stub.RecordRoute(route_iterator)print("Finished trip with %s points " % route_summary.point_count)print("Passed %s features " % route_summary.feature_count)print("Travelled %s meters " % route_summary.distance)print("It took %s seconds " % route_summary.elapsed_time)
其中route_iterator为一个迭代器。
3、双向流式RPC
双向流式RPC请求的内容为流式,返回内容也为流式,n次请求,n次返回。我们可以用迭