最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

AsyncHttpClient?RequestFilter請(qǐng)求篩選源碼解讀

 更新時(shí)間:2023年12月13日 09:57:13   作者:codecraft  
這篇文章主要為大家介紹了AsyncHttpClient?RequestFilter請(qǐng)求篩選源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

本文主要研究一下AsyncHttpClient的RequestFilter

RequestFilter

org/asynchttpclient/filter/RequestFilter.java

/**
 * A Filter interface that gets invoked before making an actual request.
 */
public interface RequestFilter {
  /**
   * An {@link org.asynchttpclient.AsyncHttpClient} will invoke {@link RequestFilter#filter} and will use the
   * returned {@link FilterContext#getRequest()} and {@link FilterContext#getAsyncHandler()} to continue the request
   * 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;
}
RequestFilter定義了filter方法

ThrottleRequestFilter

org/asynchttpclient/filter/ThrottleRequestFilter.java

/**
 * A {@link org.asynchttpclient.filter.RequestFilter} throttles requests and block when the number of permits is reached,
 * waiting for the response to arrives before executing the next request.
 */
public class ThrottleRequestFilter implements RequestFilter {
  private static final Logger logger = LoggerFactory.getLogger(ThrottleRequestFilter.class);
  private final Semaphore available;
  private final int maxWait;
  public ThrottleRequestFilter(int maxConnections) {
    this(maxConnections, Integer.MAX_VALUE);
  }
  public ThrottleRequestFilter(int maxConnections, int maxWait) {
    this(maxConnections, maxWait, false);
  }
  public ThrottleRequestFilter(int maxConnections, int maxWait, boolean fair) {
    this.maxWait = maxWait;
    available = new Semaphore(maxConnections, fair);
  }
  /**
   * {@inheritDoc}
   */
  @Override
  public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException {
    try {
      if (logger.isDebugEnabled()) {
        logger.debug("Current Throttling Status {}", available.availablePermits());
      }
      if (!available.tryAcquire(maxWait, TimeUnit.MILLISECONDS)) {
        throw new FilterException(String.format("No slot available for processing Request %s with AsyncHandler %s",
                ctx.getRequest(), ctx.getAsyncHandler()));
      }
    } catch (InterruptedException e) {
      throw new FilterException(String.format("Interrupted Request %s with AsyncHandler %s",
              ctx.getRequest(), ctx.getAsyncHandler()));
    }
    return new FilterContext.FilterContextBuilder<>(ctx)
            .asyncHandler(ReleasePermitOnComplete.wrap(ctx.getAsyncHandler(), available))
            .build();
  }
}
ThrottleRequestFilter實(shí)現(xiàn)了RequestFilter接口,它使用Semaphore來對(duì)request進(jìn)行限流,限流不通過拋出FilterException,若通過則通過ReleasePermitOnComplete.wrap(ctx.getAsyncHandler(), available)包裝一下asyncHandler以釋放信號(hào)量ReleasePermitOnComplete

ReleasePermitOnComplete

org/asynchttpclient/filter/ReleasePermitOnComplete.java

/**
 * Wrapper for {@link AsyncHandler}s to release a permit on {@link AsyncHandler#onCompleted()}. This is done via a dynamic proxy to preserve all interfaces of the wrapped handler.
 */
public class ReleasePermitOnComplete {
  /**
   * Wrap handler to release the permit of the semaphore on {@link AsyncHandler#onCompleted()}.
   *
   * @param handler   the handler to be wrapped
   * @param available the Semaphore to be released when the wrapped handler is completed
   * @param <T>       the handler result type
   * @return the wrapped handler
   */
  @SuppressWarnings("unchecked")
  public static <T> AsyncHandler<T> wrap(final AsyncHandler<T> handler, final Semaphore available) {
    Class<?> handlerClass = handler.getClass();
    ClassLoader classLoader = handlerClass.getClassLoader();
    Class<?>[] interfaces = allInterfaces(handlerClass);
    return (AsyncHandler<T>) Proxy.newProxyInstance(classLoader, interfaces, (proxy, method, args) -> {
        try {
          return method.invoke(handler, args);
        } finally {
          switch (method.getName()) {
            case "onCompleted":
            case "onThrowable":
              available.release();
            default:
          }
        }
    });
  }
  //......
}
ReleasePermitOnComplete的wrap對(duì)原來的handler進(jìn)行代理,在finally里頭執(zhí)行available.release()

preProcessRequest

org/asynchttpclient/DefaultAsyncHttpClient.java

/**
   * Configure and execute the associated {@link RequestFilter}. This class
   * may decorate the {@link Request} and {@link AsyncHandler}
   *
   * @param fc {@link FilterContext}
   * @return {@link FilterContext}
   */
  private <T> FilterContext<T> preProcessRequest(FilterContext<T> fc) throws FilterException {
    for (RequestFilter asyncFilter : config.getRequestFilters()) {
      fc = asyncFilter.filter(fc);
      assertNotNull(fc, "filterContext");
    }
    Request request = fc.getRequest();
    if (fc.getAsyncHandler() instanceof ResumableAsyncHandler) {
      request = ResumableAsyncHandler.class.cast(fc.getAsyncHandler()).adjustRequestRange(request);
    }
    if (request.getRangeOffset() != 0) {
      RequestBuilder builder = new RequestBuilder(request);
      builder.setHeader("Range", "bytes=" + request.getRangeOffset() + "-");
      request = builder.build();
    }
    fc = new FilterContext.FilterContextBuilder<>(fc).request(request).build();
    return fc;
  }
DefaultAsyncHttpClient的preProcessRequest方法遍歷config.getRequestFilters(),挨個(gè)執(zhí)行asyncFilter.filter(fc)

executeRequest

org/asynchttpclient/DefaultAsyncHttpClient.java

public <T> ListenableFuture<T> executeRequest(Request request, AsyncHandler<T> handler) {
    if (config.getCookieStore() != null) {
      try {
        List<Cookie> cookies = config.getCookieStore().get(request.getUri());
        if (!cookies.isEmpty()) {
          RequestBuilder requestBuilder = new RequestBuilder(request);
          for (Cookie cookie : cookies) {
            requestBuilder.addOrReplaceCookie(cookie);
          }
          request = requestBuilder.build();
        }
      } catch (Exception e) {
        handler.onThrowable(e);
        return new ListenableFuture.CompletedFailure<>("Failed to set cookies of request", e);
      }
    }

    if (noRequestFilters) {
      return execute(request, handler);
    } else {
      FilterContext<T> fc = new FilterContext.FilterContextBuilder<T>().asyncHandler(handler).request(request).build();
      try {
        fc = preProcessRequest(fc);
      } catch (Exception e) {
        handler.onThrowable(e);
        return new ListenableFuture.CompletedFailure<>("preProcessRequest failed", e);
      }

      return execute(fc.getRequest(), fc.getAsyncHandler());
    }
  }
executeRequest方法對(duì)于noRequestFilters為false會(huì)執(zhí)行preProcessRequest

小結(jié)

AsyncHttpClient的RequestFilter定義了filter方法,它有一個(gè)實(shí)現(xiàn)類為ThrottleRequestFilter,使用信號(hào)量用于對(duì)請(qǐng)求進(jìn)行限流;

DefaultAsyncHttpClient的executeRequest方法對(duì)于noRequestFilters為false會(huì)執(zhí)行preProcessRequest,而preProcessRequest方法遍歷config.getRequestFilters(),挨個(gè)執(zhí)行asyncFilter.filter(fc)。

以上就是AsyncHttpClient RequestFilter請(qǐng)求篩選源碼解讀的詳細(xì)內(nèi)容,更多關(guān)于AsyncHttpClient RequestFilter的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java中如何自定義一個(gè)類加載器加載自己指定的類

    Java中如何自定義一個(gè)類加載器加載自己指定的類

    這篇文章主要給大家介紹了關(guān)于Java中如何自定義一個(gè)類加載器加載自己指定的類,自定義類加載器允許我們加載特定路徑的類文件,并且可以用于插件系統(tǒng)、熱部署和隔離加載等場(chǎng)景,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-12-12
  • java-RGB調(diào)色面板的實(shí)現(xiàn)(事件監(jiān)聽器之匿名內(nèi)部類)

    java-RGB調(diào)色面板的實(shí)現(xiàn)(事件監(jiān)聽器之匿名內(nèi)部類)

    這篇文章主要介紹了java-RGB調(diào)色面板的實(shí)現(xiàn)(事件監(jiān)聽器之匿名內(nèi)部類),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Java WeakHashMap案例詳解

    Java WeakHashMap案例詳解

    這篇文章主要介紹了Java WeakHashMap案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Java連接數(shù)據(jù)庫(kù)oracle中文亂碼解決方案

    Java連接數(shù)據(jù)庫(kù)oracle中文亂碼解決方案

    這篇文章主要介紹了Java連接數(shù)據(jù)庫(kù)oracle中文亂碼解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • spring通過jdbc連接數(shù)據(jù)庫(kù)

    spring通過jdbc連接數(shù)據(jù)庫(kù)

    這篇文章主要為大家詳細(xì)介紹了spring通過jdbc連接數(shù)據(jù)庫(kù)的相關(guān)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • java中字符串參數(shù)化符號(hào)${}的解析

    java中字符串參數(shù)化符號(hào)${}的解析

    這篇文章主要給大家介紹了java中字符串參數(shù)化符號(hào)${}是如何解析的,文中給出了詳細(xì)的分析與解決代碼,有需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-01-01
  • Spring Boot 2.0快速構(gòu)建服務(wù)組件全步驟

    Spring Boot 2.0快速構(gòu)建服務(wù)組件全步驟

    這篇文章主要給大家介紹了關(guān)于Spring Boot 2.0快速構(gòu)建服務(wù)組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot 2.0具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Nacos配置中心設(shè)計(jì)原理分析

    Nacos配置中心設(shè)計(jì)原理分析

    今天分享一下Nacos配置變更的相關(guān)知識(shí)點(diǎn),現(xiàn)在使用Java生態(tài)如果使用微服務(wù),如果部署在K8s上,那么可能會(huì)使用ConfigMap來存儲(chǔ)配置文件,如果沒有使用K8s,那么基本上都使用Nacos來做配置中心,所以有必要了解一下Nacos的配置的知識(shí)點(diǎn),本文只是對(duì)其中的部分實(shí)現(xiàn)原理進(jìn)行分析
    2023-10-10
  • 詳解Java中的不可變對(duì)象

    詳解Java中的不可變對(duì)象

    這篇文章主要介紹了Java中的不可變對(duì)象的相關(guān)知識(shí),文中代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以參考下
    2020-06-06
  • java面試題——詳解HashMap和Hashtable 的區(qū)別

    java面試題——詳解HashMap和Hashtable 的區(qū)別

    本篇文章主要介紹了java中HashMap和Hashtable的區(qū)別,具有一定的參考價(jià)值,有需要的可以了解一下。
    2016-11-11

最新評(píng)論

治县。| 松滋市| 宜丰县| 迭部县| 镇雄县| 宿松县| 博白县| 山阴县| 修水县| 乌鲁木齐县| 安龙县| 辽源市| 滕州市| 庆阳市| 晋江市| 株洲市| 宣化县| 高碑店市| 肥城市| 额敏县| 竹山县| 民县| 沭阳县| 于都县| 黄冈市| 磐石市| 天水市| 舟曲县| 华安县| 岳普湖县| 庆云县| 南阳市| 高青县| 五河县| 颍上县| 田阳县| 武穴市| 毕节市| 静安区| 通州区| 武功县|