AsyncHttpClient IOExceptionFilter异常过滤器

 更新时间:2023年12月13日 09:34:57   作者:codecraft  
这篇文章主要为大家介绍了AsyncHttpClient IOExceptionFilter异常过滤器代码流程解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下AsyncHttpClient的IOExceptionFilter

IOExceptionFilter

org/asynchttpclient/filter/IOExceptionFilter.java

/**
 * This filter is invoked when an {@link java.io.IOException} occurs during an http transaction.
 */
public interface IOExceptionFilter {
  /**
   * An {@link org.asynchttpclient.AsyncHttpClient} will invoke {@link IOExceptionFilter#filter} and will
   * use the returned {@link FilterContext} to replay the {@link org.asynchttpclient.Request} or abort the processing.
   *
   * @param ctx a {@link FilterContext}
   * @param <T> the handler result type
   * @return {@link FilterContext}. The {@link FilterContext} instance may not the same as the original one.
   * @throws FilterException to interrupt the filter processing.
   */
  <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException;
}
IOExceptionFilter接口定义了filter方法,在捕获到IOException的时候执行

ResumableIOExceptionFilter

org/asynchttpclient/handler/resumable/ResumableIOExceptionFilter.java

/**
 * Simple {@link org.asynchttpclient.filter.IOExceptionFilter} that replay the current {@link org.asynchttpclient.Request} using a {@link ResumableAsyncHandler}
 */
public class ResumableIOExceptionFilter implements IOExceptionFilter {
  public <T> FilterContext<T> filter(FilterContext<T> ctx) {
    if (ctx.getIOException() != null && ctx.getAsyncHandler() instanceof ResumableAsyncHandler) {

      Request request = ResumableAsyncHandler.class.cast(ctx.getAsyncHandler()).adjustRequestRange(ctx.getRequest());

      return new FilterContext.FilterContextBuilder<>(ctx).request(request).replayRequest(true).build();
    }
    return ctx;
  }
}
ResumableIOExceptionFilter实现了IOExceptionFilter接口,它在asyncHandler是ResumableAsyncHandler类型的时候执行adjustRequestRange方法获取新的request,然后再通过new FilterContext.FilterContextBuilder<>(ctx).request(request).replayRequest(true).build()返回

ResumableAsyncHandler

org/asynchttpclient/handler/resumable/ResumableAsyncHandler.java

/**
   * Invoke this API if you want to set the Range header on your {@link Request} based on the last valid bytes
   * position.
   *
   * @param request {@link Request}
   * @return a {@link Request} with the Range header properly set.
   */
  public Request adjustRequestRange(Request request) {
    Long ri = resumableIndex.get(request.getUrl());
    if (ri != null) {
      byteTransferred.set(ri);
    }
    // The Resumable
    if (resumableListener != null && resumableListener.length() > 0 && byteTransferred.get() != resumableListener.length()) {
      byteTransferred.set(resumableListener.length());
    }
    RequestBuilder builder = new RequestBuilder(request);
    if (request.getHeaders().get(RANGE) == null && byteTransferred.get() != 0) {
      builder.setHeader(RANGE, "bytes=" + byteTransferred.get() + "-");
    }
    return builder.build();
  }
adjustRequestRange方法在byteTransferred不等于resumableListener.length()的时候会重置byteTransferred,对于有range的header则重置其bytes参数值

ResponseFiltersInterceptor

org/asynchttpclient/netty/handler/intercept/ResponseFiltersInterceptor.java

public boolean exitAfterProcessingFilters(Channel channel,
                                            NettyResponseFuture<?> future,
                                            AsyncHandler<?> handler,
                                            HttpResponseStatus status,
                                            HttpHeaders responseHeaders) {
    FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(handler).request(future.getCurrentRequest()).responseStatus(status)
            .responseHeaders(responseHeaders).build();
    for (ResponseFilter asyncFilter : config.getResponseFilters()) {
      try {
        fc = asyncFilter.filter(fc);
        // FIXME Is it worth protecting against this?
        assertNotNull("fc", "filterContext");
      } catch (FilterException efe) {
        requestSender.abort(channel, future, efe);
      }
    }
    // The handler may have been wrapped.
    future.setAsyncHandler(fc.getAsyncHandler());
    // The request has changed
    if (fc.replayRequest()) {
      requestSender.replayRequest(future, fc, channel);
      return true;
    }
    return false;
  }
ResponseFiltersInterceptor的exitAfterProcessingFilters方法,对于fc.replayRequest()为true则执行requestSender.replayRequest(future, fc, channel)

replayRequest

org/asynchttpclient/netty/request/NettyRequestSender.java

public void replayRequest(final NettyResponseFuture<?> future, FilterContext fc, Channel channel) {

    Request newRequest = fc.getRequest();
    future.setAsyncHandler(fc.getAsyncHandler());
    future.setChannelState(ChannelState.NEW);
    future.touch();

    LOGGER.debug("\n\nReplaying Request {}\n for Future {}\n", newRequest, future);
    try {
      future.getAsyncHandler().onRetry();
    } catch (Exception e) {
      LOGGER.error("onRetry crashed", e);
      abort(channel, future, e);
      return;
    }

    channelManager.drainChannelAndOffer(channel, future);
    sendNextRequest(newRequest, future);
  }
NettyRequestSender的replayRequest方法会触发future.getAsyncHandler().onRetry()回调,然后执行channelManager.drainChannelAndOffer(channel, future)及sendNextRequest

applyIoExceptionFiltersAndReplayRequest

org/asynchttpclient/netty/request/NettyRequestSender.java

public boolean applyIoExceptionFiltersAndReplayRequest(NettyResponseFuture<?> future, IOException e,
                                                         Channel channel) {
    boolean replayed = false;
    @SuppressWarnings({"unchecked", "rawtypes"})
    FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
            .request(future.getCurrentRequest()).ioException(e).build();
    for (IOExceptionFilter asyncFilter : config.getIoExceptionFilters()) {
      try {
        fc = asyncFilter.filter(fc);
        assertNotNull(fc, "filterContext");
      } catch (FilterException efe) {
        abort(channel, future, efe);
      }
    }
    if (fc.replayRequest() && future.incrementRetryAndCheck() && future.isReplayPossible()) {
      future.setKeepAlive(false);
      replayRequest(future, fc, channel);
      replayed = true;
    }
    return replayed;
  }
NettyRequestSender的applyIoExceptionFiltersAndReplayRequest方法会遍历config.getIoExceptionFilters(),然后挨个执行fc = asyncFilter.filter(fc)

小结

AsyncHttpClient的IOExceptionFilter接口定义了filter方法,在捕获到IOException的时候执行;

ResumableIOExceptionFilter实现了IOExceptionFilter接口,它在asyncHandler是ResumableAsyncHandler类型的时候执行adjustRequestRange方法获取新的request,然后再通过new FilterContext.FilterContextBuilder<>(ctx).request(request).replayRequest(true).build()返回;

NettyRequestSender的replayRequest方法会触发future.getAsyncHandler().onRetry()回调,然后执行channelManager.drainChannelAndOffer(channel, future)及sendNextRequest。

以上就是AsyncHttpClient IOExceptionFilter异常过滤器的详细内容,更多关于AsyncHttpClient IOExceptionFilter的资料请关注脚本之家其它相关文章!

相关文章

  • Springboot中使用Filter实现Header认证详解

    Springboot中使用Filter实现Header认证详解

    这篇文章主要介绍了Springboot中使用Filter实现Header认证详解,当在 web.xml 注册了一个 Filter 来对某个 Servlet 程序进行拦截处理时,它可以决定是否将请求继续传递给 Servlet 程序,以及对请求和响应消息是否进行修改,需要的朋友可以参考下
    2023-08-08
  • jar命令的用法详解

    jar命令的用法详解

    这篇文章主要介绍了jar命令的用法,非常实用,需要的朋友可以参考下
    2014-08-08
  • 关于分布式锁(Redisson)的原理分析

    关于分布式锁(Redisson)的原理分析

    这篇文章主要介绍了关于分布式锁(Redisson)的原理,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • 详解Spring中singleton bean如何同时服务多个请求

    详解Spring中singleton bean如何同时服务多个请求

    这篇文章主要介绍了详解Spring中singleton bean如何同时服务多个请求
    2023-02-02
  • java实现2048小游戏

    java实现2048小游戏

    这篇文章主要为大家详细介绍了java实现2048小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-02-02
  • Java多线程Callable和Future接口区别

    Java多线程Callable和Future接口区别

    这篇文章主要介绍了Java多线程Callable和Future接口区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • 深入解析Jdk8中Stream流的使用让你脱离for循环

    深入解析Jdk8中Stream流的使用让你脱离for循环

    这篇文章主要介绍了Jdk8中Stream流的使用,让你脱离for循环,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • EasyExcel工具读取Excel空数据行问题的解决办法

    EasyExcel工具读取Excel空数据行问题的解决办法

    EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单,节省内存著称,下面这篇文章主要给大家介绍了关于EasyExcel工具读取Excel空数据行问题的解决办法,需要的朋友可以参考下
    2022-08-08
  • java异步编程CompletableFuture使用示例详解

    java异步编程CompletableFuture使用示例详解

    这篇文章主要为大家介绍了java异步编程CompletableFuture使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • MyBatis入门学习教程(一)-MyBatis快速入门

    MyBatis入门学习教程(一)-MyBatis快速入门

    MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架,这篇文章主要给大家分享MyBatis入门学习教程(一)-MyBatis快速入门,需要的朋友可以参考下
    2015-08-08

最新评论