reactor-netty中HttpClient对TcpClient的封装

前端之家收集整理的这篇文章主要介绍了reactor-netty中HttpClient对TcpClient的封装前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文主要研究一下reactor-netty中HttpClient对TcpClien的封装

maven

  1. <dependency>
  2. <groupId>io.projectreactor.ipc</groupId>
  3. <artifactId>reactor-netty</artifactId>
  4. <version>0.7.3.RELEASE</version>
  5. </dependency>

实例

  1. HttpClient client = HttpClient.create();
  2. Mono<HttpClientResponse> mono = client.get("http://baidu.com");
  3. //NOTE reactor.ipc.netty.http.client.MonoHttpClientResponse
  4. LOGGER.info("mono resp:{}",mono.getClass());
  5. mono.subscribe();

HttpClient.request

reactor-netty-0.7.3.RELEASE-sources.jar!/reactor/ipc/netty/http/client/HttpClient.java

  1. /**
  2. * Use the passed HTTP method to send to the given URL. When connection has been made,* the passed handler is invoked and can be used to tune the request and
  3. * write data to it.
  4. *
  5. * @param method the HTTP method to send
  6. * @param url the target remote URL
  7. * @param handler the {@link Function} to invoke on opened TCP connection
  8. * @return a {@link Mono} of the {@link HttpServerResponse} ready to consume for
  9. * response
  10. */
  11. public Mono<HttpClientResponse> request(HttpMethod method,String url,Function<? super HttpClientRequest,? extends Publisher<Void>> handler) {
  12.  
  13. if (method == null || url == null) {
  14. throw new IllegalArgumentException("Method && url cannot be both null");
  15. }
  16.  
  17. return new MonoHttpClientResponse(this,url,method,handler(handler,options));
  18. }

Mono.subscribe

reactor-core-3.1.3.RELEASE-sources.jar!/reactor/core/publisher/Mono.java

  1. /**
  2. * Subscribe to this {@link Mono} and request unbounded demand.
  3. * <p>
  4. * This version doesn't specify any consumption behavior for the events from the
  5. * chain,especially no error handling,so other variants should usually be preferred.
  6. *
  7. * <p>
  8. * <img width="500" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.3.RELEASE/src/docs/marble/unbounded1.png" alt="">
  9. * <p>
  10. *
  11. * @return a new {@link Disposable} that can be used to cancel the underlying {@link Subscription}
  12. */
  13. public final Disposable subscribe() {
  14. if(this instanceof MonoProcessor){
  15. MonoProcessor<T> s = (MonoProcessor<T>)this;
  16. s.connect();
  17. return s;
  18. }
  19. else{
  20. return subscribeWith(new LambdaMonoSubscriber<>(null,null,null));
  21. }
  22. }
这里调用了subscribeWith,创建了一个LambdaMonoSubscriber
  1. /**
  2. * Subscribe the given {@link Subscriber} to this {@link Mono} and return said
  3. * {@link Subscriber} (eg. a {@link MonoProcessor}).
  4. *
  5. * @param subscriber the {@link Subscriber} to subscribe with
  6. * @param <E> the reified type of the {@link Subscriber} for chaining
  7. *
  8. * @return the passed {@link Subscriber} after subscribing it to this {@link Mono}
  9. */
  10. public final <E extends Subscriber<? super T>> E subscribeWith(E subscriber) {
  11. subscribe(subscriber);
  12. return subscriber;
  13. }
  14. public final void subscribe(Subscriber<? super T> actual) {
  15. onLastAssembly(this).subscribe(Operators.toCoreSubscriber(actual));
  16. }
这个onLastAssembly(this).subscribe调用的是子类的方法

MonoHttpClientResponse.subscribe

reactor-netty-0.7.3.RELEASE-sources.jar!/reactor/ipc/netty/http/client/MonoHttpClientResponse.java

  1. public void subscribe(final CoreSubscriber<? super HttpClientResponse> subscriber) {
  2. ReconnectableBridge bridge = new ReconnectableBridge();
  3. bridge.activeURI = startURI;
  4.  
  5. Mono.defer(() -> parent.client.newHandler(new HttpClientHandler(this,bridge),parent.options.getRemoteAddress(bridge.activeURI),HttpClientOptions.isSecure(bridge.activeURI),bridge))
  6. .retry(bridge)
  7. .cast(HttpClientResponse.class)
  8. .subscribe(subscriber);
  9. }
这里使用Mono.defer又对client.newHandler包装了下,defer的英文原意是 Defers the creation of the actual Publisher the Subscriber will be subscribed to.,也就是延迟publisher的创建

这里的subscriber便是Operators.toCoreSubscriber(lambdaMonoSubscriber)

可以看到这里调用了parent的client.newHandler,这里的parent便是HttpClient,里头的client是TcpClient

retry使用的是ReconnectableBridge,handler使用的是HttpClientHandler

MonoHttpClientResponse#ReconnectableBridge

  1. static final class ReconnectableBridge
  2. implements Predicate<Throwable>,Consumer<Channel> {
  3.  
  4. volatile URI activeURI;
  5. volatile String[] redirectedFrom;
  6.  
  7. ReconnectableBridge() {
  8. }
  9.  
  10. void redirect(String to) {
  11. String[] redirectedFrom = this.redirectedFrom;
  12. URI from = activeURI;
  13. try {
  14. activeURI = new URI(to);
  15. }
  16. catch (URISyntaxException e) {
  17. throw Exceptions.propagate(e);
  18. }
  19. if (redirectedFrom == null) {
  20. this.redirectedFrom = new String[]{from.toString()};
  21. }
  22. else {
  23. String[] newRedirectedFrom = new String[redirectedFrom.length + 1];
  24. System.arraycopy(redirectedFrom,newRedirectedFrom,redirectedFrom.length);
  25. newRedirectedFrom[redirectedFrom.length] = from.toString();
  26. this.redirectedFrom = newRedirectedFrom;
  27. }
  28. }
  29.  
  30. @Override
  31. public void accept(Channel channel) {
  32. String[] redirectedFrom = this.redirectedFrom;
  33. if (redirectedFrom != null) {
  34. channel.attr(HttpClientOperations.REDIRECT_ATTR_KEY)
  35. .set(redirectedFrom);
  36. }
  37. }
  38.  
  39. @Override
  40. public boolean test(Throwable throwable) {
  41. if (throwable instanceof RedirectClientException) {
  42. RedirectClientException re = (RedirectClientException) throwable;
  43. redirect(re.location);
  44. return true;
  45. }
  46. if (AbortedException.isConnectionReset(throwable)) {
  47. redirect(activeURI.toString());
  48. return true;
  49. }
  50. return false;
  51. }
  52. }
这里看好像是处理redirect的,并不是真正意义上的retry,比如retry多少次之类的

MonoHttpClientResponse#HttpClientHandler

reactor-netty-0.7.3.RELEASE-sources.jar!/reactor/ipc/netty/http/client/MonoHttpClientResponse.java

  1. static final class HttpClientHandler
  2. implements BiFunction<NettyInbound,NettyOutbound,Publisher<Void>> {
  3.  
  4. final MonoHttpClientResponse parent;
  5. final ReconnectableBridge bridge;
  6.  
  7. HttpClientHandler(MonoHttpClientResponse parent,ReconnectableBridge bridge) {
  8. this.bridge = bridge;
  9. this.parent = parent;
  10. }
  11.  
  12. @Override
  13. public Publisher<Void> apply(NettyInbound in,NettyOutbound out) {
  14. try {
  15. URI uri = bridge.activeURI;
  16. HttpClientOperations ch = (HttpClientOperations) in;
  17. String host = uri.getHost();
  18. int port = uri.getPort();
  19. if (port != -1 && port != 80 && port != 443) {
  20. host = host + ':' + port;
  21. }
  22. ch.getNettyRequest()
  23. .setUri(uri.getRawPath() + (uri.getQuery() == null ? "" :
  24. "?" + uri.getRawQuery()))
  25. .setMethod(parent.method)
  26. .setProtocolVersion(HttpVersion.HTTP_1_1)
  27. .headers()
  28. .add(HttpHeaderNames.HOST,host)
  29. .add(HttpHeaderNames.ACCEPT,ALL);
  30.  
  31. if (parent.method == HttpMethod.GET
  32. || parent.method == HttpMethod.HEAD
  33. || parent.method == HttpMethod.DELETE) {
  34. ch.chunkedTransfer(false);
  35. }
  36.  
  37. if (parent.handler != null) {
  38. return parent.handler.apply(ch);
  39. }
  40. else {
  41. return ch.send();
  42. }
  43. }
  44. catch (Throwable t) {
  45. return Mono.error(t);
  46. }
  47. }
  48.  
  49. @Override
  50. public String toString() {
  51. return "HttpClientHandler{" + "startURI=" + bridge.activeURI + ",method=" + parent.method + ",handler=" + parent.handler + '}';
  52. }
  53.  
  54. }
这里的handler可以看到netty的痕迹,最后是直接调用HttpClientOperations.send方法

reactor-netty-0.7.3.RELEASE-sources.jar!/reactor/ipc/netty/http/client/HttpClientOperations.java

  1. public Mono<Void> send() {
  2. if (markSentHeaderAndBody()) {
  3. HttpMessage request = newFullEmptyBodyMessage();
  4. return FutureMono.deferFuture(() -> channel().writeAndFlush(request));
  5. }
  6. else {
  7. return Mono.empty();
  8. }
  9. }
最后调用netty的channel().writeAndFlush(request)将请求发送出去

小结

reactor-netty中的HttpClient对TcpClient进行了桥接,而TcpClient则是基于netty来实现。

猜你在找的React相关文章