简体   繁体   中英

gRPC server streaming for 1 message

I saw this example on the internet and was wondering, why would you use a stream to just send 1 message back? Isn't it more efficient to just return unary?

@Override
public void getFeature(Point request, StreamObserver<Feature> responseObserver) {
  responseObserver.onNext(checkFeature(request));
  responseObserver.onCompleted();
}

...

private Feature checkFeature(Point location) {
  for (Feature feature : features) {
    if (feature.getLocation().getLatitude() == location.getLatitude()
        && feature.getLocation().getLongitude() == location.getLongitude()) {
      return feature;
    }
  }

  // No feature was found, return an unnamed feature.
  return Feature.newBuilder().setName("").setLocation(location).build();
}

source: https://grpc.io/docs/tutorials/basic/java/

First of all the example is there to illustrate the streaming concept. In this particular case it just so happens that it ended up sending only one message back. However the API needs to be designed for the most general case where for a given location there could be multiple Features and for some reason they cannot be combined into an array in a unary response.

Okay, apparently I got confused between the differences of gRPC in Java and C#. I am used to developing in C#, but in Java, for Unary gRPC, they use the streamObserver object to respond. This is quite confusing...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM