《Apache Dubbo微服务开发从入门到精通》——通信协议——二、 HTTP/2(Triple)协议(8) https://developer.aliyun.com/article/1224937
3) 非Protobuf序列化的流
a) API
注:
Stream方法的方法入参和返回值是严格约定的,为防止写错而导致问题,Dubbo3框架侧做了对参数的检查, 如果出错则会抛出异常。
对于双向流(BIDIRECTIONAL_STREAM),需要注意参数中的StreamObserver是响应流,返回参数中的StreamObserver为请求流。
b) 实现类
public class WrapGreeterImpl implements WrapGreeter { //... @Override public StreamObserver<String> sayHelloStream(StreamObserver<String> response) { return new StreamObserver<String>() { @Override public void onNext(String data) { System.out.println(data); response.onNext("hello,"+data); } @Override public void onError(Throwable throwable) { throwable.printStackTrace(); } @Override public void onCompleted() { System.out.println("onCompleted"); response.onCompleted(); } }; } @Override public void sayHelloServerStream(String request, StreamObserver<String> response) { for (int i = 0; i < 10; i++) { response.onNext("hello," + request); } response.onCompleted(); } }
c) 调用方式
delegate.sayHelloServerStream("server stream", new StreamObserver<String>() { @Override public void onNext(String data) { System.out.println(data); } @Override public void onError(Throwable throwable) { throwable.printStackTrace(); } @Override public void onCompleted() { System.out.println("onCompleted"); } }); StreamObserver<String> request = delegate.sayHelloStream(new StreamObserver<String>() { @Override public void onNext(String data) { System.out.println(data); } @Override public void onError(Throwable throwable) { throwable.printStackTrace(); } @Override public void onCompleted() { System.out.println("onCompleted"); } }); for (int i = 0; i < n; i++) { request.onNext("stream request" + i); } request.onCompleted();