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

httpclient的監(jiān)控流程源碼解讀

 更新時間:2023年10月08日 08:31:23   作者:codecraft  
這篇文章主要為大家介紹了httpclient的監(jiān)控流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

本文主要研究一下如何監(jiān)控httpclient

MicrometerHttpRequestExecutor

micrometer-core-1.3.0-sources.jar!/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpRequestExecutor.java

@Incubating(since = "1.2.0")
public class MicrometerHttpRequestExecutor extends HttpRequestExecutor {
    /**
     * Default header name for URI pattern.
     */
    public static final String DEFAULT_URI_PATTERN_HEADER = "URI_PATTERN";
    private static final String METER_NAME = "httpcomponents.httpclient.request";
    private static final String UNKNOWN = "UNKNOWN";
    private static final Tag STATUS_UNKNOWN = Tag.of("status", UNKNOWN);
    private static final Tag STATUS_CLIENT_ERROR = Tag.of("status", "CLIENT_ERROR");
    private static final Tag STATUS_IO_ERROR = Tag.of("status", "IO_ERROR");
    private final MeterRegistry registry;
    private final Function<HttpRequest, String> uriMapper;
    private final Iterable<Tag> extraTags;
    private final boolean exportTagsForRoute;
    /**
     * Use {@link #builder(MeterRegistry)} to create an instance of this class.
     */
    private MicrometerHttpRequestExecutor(int waitForContinue,
                                          MeterRegistry registry,
                                          Function<HttpRequest, String> uriMapper,
                                          Iterable<Tag> extraTags,
                                          boolean exportTagsForRoute) {
        super(waitForContinue);
        this.registry = Optional.ofNullable(registry).orElseThrow(() -> new IllegalArgumentException("registry is required but has been initialized with null"));
        this.uriMapper = Optional.ofNullable(uriMapper).orElseThrow(() -> new IllegalArgumentException("uriMapper is required but has been initialized with null"));
        this.extraTags = Optional.ofNullable(extraTags).orElse(Collections.emptyList());
        this.exportTagsForRoute = exportTagsForRoute;
    }
    //......
}
MicrometerHttpRequestExecutor繼承了HttpRequestExecutor,它覆蓋了execute方法,使用timer來監(jiān)控,定義了method、uri、status、routeTags(target.scheme、target.host、target.port)、extraTags這幾個tag,metric名為httpcomponents.httpclient.request。
HttpClientBuilder.create()
          .setRequestExecutor(MicrometerHttpRequestExecutor
                  .builder(meterRegistry)
                  .build())
          .build();
具體使用可以通過setRequestExecutor來設(shè)置MicrometerHttpRequestExecutor

Builder

public static Builder builder(MeterRegistry registry) {
        return new Builder(registry);
    }
    public static class Builder {
        private final MeterRegistry registry;
        private int waitForContinue = HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE;
        private Iterable<Tag> tags = Collections.emptyList();
        private Function<HttpRequest, String> uriMapper = new DefaultUriMapper();
        private boolean exportTagsForRoute = false;
        Builder(MeterRegistry registry) {
            this.registry = registry;
        }
        /**
         * @param waitForContinue Overrides the wait for continue time for this
         *                        request executor. See {@link HttpRequestExecutor}
         *                        for details.
         * @return This builder instance.
         */
        public Builder waitForContinue(int waitForContinue) {
            this.waitForContinue = waitForContinue;
            return this;
        }
        /**
         * @param tags Additional tags which should be exposed with every value.
         * @return This builder instance.
         */
        public Builder tags(Iterable<Tag> tags) {
            this.tags = tags;
            return this;
        }
        /**
         * Allows to register a mapping function for exposing request URIs. Be
         * careful, exposing request URIs could result in a huge number of tag
         * values, which could cause problems in your meter registry.
         *
         * By default, this feature is almost disabled. It only exposes values
         * of the {@link #DEFAULT_URI_PATTERN_HEADER} HTTP header.
         *
         * @param uriMapper A mapper that allows mapping and exposing request
         *                  paths.
         * @return This builder instance.
         * @see DefaultUriMapper
         */
        public Builder uriMapper(Function<HttpRequest, String> uriMapper) {
            this.uriMapper = uriMapper;
            return this;
        }
        /**
         * Allows to expose the target scheme, host and port with every metric.
         * Be careful with enabling this feature: If your client accesses a huge
         * number of remote servers, this would result in a huge number of tag
         * values, which could cause cardinality problems.
         *
         * By default, this feature is disabled.
         *
         * @param exportTagsForRoute Set this to true, if the metrics should be
         *                           tagged with the target route.
         * @return This builder instance.
         */
        public Builder exportTagsForRoute(boolean exportTagsForRoute) {
            this.exportTagsForRoute = exportTagsForRoute;
            return this;
        }
        /**
         * @return Creates an instance of {@link MicrometerHttpRequestExecutor}
         * with all the configured properties.
         */
        public MicrometerHttpRequestExecutor build() {
            return new MicrometerHttpRequestExecutor(waitForContinue, registry, uriMapper, tags, exportTagsForRoute);
        }
    }
MicrometerHttpRequestExecutor提供了builder方法,可以設(shè)置waitForContinue、tags、uriMapper(默認(rèn)是DefaultUriMapper)、exportTagsForRoute

DefaultUriMapper

/**
     * Extracts the pattern from the request header of the request if available.
     */
    private static class DefaultUriMapper implements Function<HttpRequest, String> {
        @Override
        public String apply(HttpRequest httpRequest) {
            Header uriPattern = httpRequest.getLastHeader(DEFAULT_URI_PATTERN_HEADER);
            if (uriPattern != null && uriPattern.getValue() != null) {
                return uriPattern.getValue();
            }
            return UNKNOWN;
        }
    }
DefaultUriMapper用于獲取uriPattern

MicrometerHttpClientInterceptor

micrometer-core-1.5.9.jar!/io/micrometer/core/instrument/binder/httpcomponents/MicrometerHttpClientInterceptor.java

@Incubating(
    since = "1.4.0"
)
public class MicrometerHttpClientInterceptor {
    private static final String METER_NAME = "httpcomponents.httpclient.request";
    private final Map<HttpContext, Timer.Sample> timerByHttpContext;
    private final HttpRequestInterceptor requestInterceptor;
    private final HttpResponseInterceptor responseInterceptor;
    public MicrometerHttpClientInterceptor(MeterRegistry meterRegistry, Function<HttpRequest, String> uriMapper, Iterable<Tag> extraTags, boolean exportTagsForRoute) {
        this.timerByHttpContext = new ConcurrentHashMap();
        this.requestInterceptor = (request, context) -> {
            this.timerByHttpContext.put(context, Timer.start(meterRegistry).tags(new String[]{"method", request.getRequestLine().getMethod(), "uri", (String)uriMapper.apply(request)}));
        };
        this.responseInterceptor = (response, context) -> {
            Timer.Sample sample = (Timer.Sample)this.timerByHttpContext.remove(context);
            sample.stop(meterRegistry, Timer.builder("httpcomponents.httpclient.request").tag("status", Integer.toString(response.getStatusLine().getStatusCode())).tags(exportTagsForRoute ? HttpContextUtils.generateTagsForRoute(context) : Tags.empty()).tags(extraTags));
        };
    }
    public MicrometerHttpClientInterceptor(MeterRegistry meterRegistry, Iterable<Tag> extraTags, boolean exportTagsForRoute) {
        this(meterRegistry, new DefaultUriMapper(), extraTags, exportTagsForRoute);
    }
    public HttpRequestInterceptor getRequestInterceptor() {
        return this.requestInterceptor;
    }
    public HttpResponseInterceptor getResponseInterceptor() {
        return this.responseInterceptor;
    }
}
micrometer1.4.0版本開始提供了MicrometerHttpClientInterceptor,它定義了requestInterceptor、responseInterceptor,通過timer來上報名為httpcomponents.httpclient.request,tag為method、uri、status、exportTagsForRoute、extraTags的指標(biāo)

PoolingHttpClientConnectionManagerMetricsBinder

io/micrometer/core/instrument/binder/httpcomponents/PoolingHttpClientConnectionManagerMetricsBinder.java

public class PoolingHttpClientConnectionManagerMetricsBinder implements MeterBinder {
    private final PoolingHttpClientConnectionManager connectionManager;
    private final Iterable<Tag> tags;
    /**
     * Creates a metrics binder for the given pooling connection manager.
     *
     * @param connectionManager The connection manager to monitor.
     * @param name Name of the connection manager. Will be added as tag with the
     *             key "httpclient".
     * @param tags Tags to apply to all recorded metrics. Must be an even number
     *             of arguments representing key/value pairs of tags.
     */
    @SuppressWarnings("WeakerAccess")
    public PoolingHttpClientConnectionManagerMetricsBinder(PoolingHttpClientConnectionManager connectionManager, String name, String... tags) {
        this(connectionManager, name, Tags.of(tags));
    }
    /**
     * Creates a metrics binder for the given pooling connection manager.
     *
     * @param connectionManager The connection manager to monitor.
     * @param name Name of the connection manager. Will be added as tag with the
     *             key "httpclient".
     * @param tags Tags to apply to all recorded metrics.
     */
    @SuppressWarnings("WeakerAccess")
    public PoolingHttpClientConnectionManagerMetricsBinder(PoolingHttpClientConnectionManager connectionManager, String name, Iterable<Tag> tags) {
        this.connectionManager = connectionManager;
        this.tags = Tags.concat(tags, "httpclient", name);
    }
    @Override
    public void bindTo(@NonNull MeterRegistry registry) {
        registerTotalMetrics(registry);
    }
    private void registerTotalMetrics(MeterRegistry registry) {
        Gauge.builder("httpcomponents.httpclient.pool.total.max",
            connectionManager,
            (connectionManager) -> connectionManager.getTotalStats().getMax())
            .description("The configured maximum number of allowed persistent connections for all routes.")
            .tags(tags)
            .register(registry);
        Gauge.builder("httpcomponents.httpclient.pool.total.connections",
            connectionManager,
            (connectionManager) -> connectionManager.getTotalStats().getAvailable())
            .description("The number of persistent and leased connections for all routes.")
            .tags(tags).tag("state", "available")
            .register(registry);
        Gauge.builder("httpcomponents.httpclient.pool.total.connections",
            connectionManager,
            (connectionManager) -> connectionManager.getTotalStats().getLeased())
            .description("The number of persistent and leased connections for all routes.")
            .tags(tags).tag("state", "leased")
            .register(registry);
        Gauge.builder("httpcomponents.httpclient.pool.total.pending",
            connectionManager,
            (connectionManager) -> connectionManager.getTotalStats().getPending())
            .description("The number of connection requests being blocked awaiting a free connection for all routes.")
            .tags(tags)
            .register(registry);
        Gauge.builder("httpcomponents.httpclient.pool.route.max.default",
            connectionManager,
            PoolingHttpClientConnectionManager::getDefaultMaxPerRoute)
            .description("The configured default maximum number of allowed persistent connections per route.")
            .tags(tags)
            .register(registry);
    }
}
PoolingHttpClientConnectionManagerMetricsBinder實現(xiàn)了MeterBinder接口,它構(gòu)造器接收PoolingHttpClientConnectionManager、name、tags,其bindTo方法定義了如下幾個metrics
  • httpcomponents.httpclient.pool.total.max
  • httpcomponents.httpclient.pool.total.connections, tag:state=available
  • httpcomponents.httpclient.pool.total.connections, tag:state=leased
  • httpcomponents.httpclient.pool.total.pending
  • httpcomponents.httpclient.pool.route.max.default

小結(jié)

micrometer為apache httpclient提供了對應(yīng)的binder,用于上報相關(guān)metrics,其中1.2.0版本提供了MicrometerHttpRequestExecutor(httpcomponents.httpclient.request),1.4.0版本提供了MicrometerHttpClientInterceptor(httpcomponents.httpclient.request),另外對于連接池提供了PoolingHttpClientConnectionManagerMetricsBinder(httpcomponents.httpclient.pool)進(jìn)行監(jiān)控上報。

以上就是httpclient的監(jiān)控的詳細(xì)內(nèi)容,更多關(guān)于httpclient監(jiān)控的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java實現(xiàn)簡單訂餐系統(tǒng)

    Java實現(xiàn)簡單訂餐系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)簡單訂餐系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • 深入Java Final

    深入Java Final

    本篇文章,小編將為大家介紹Java Final,有需要的朋友可以參考一下
    2013-04-04
  • 關(guān)于Long和Integer相互轉(zhuǎn)換方式

    關(guān)于Long和Integer相互轉(zhuǎn)換方式

    這篇文章主要介紹了關(guān)于Long和Integer相互轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Java并發(fā)編程Callable與Future的應(yīng)用實例代碼

    Java并發(fā)編程Callable與Future的應(yīng)用實例代碼

    這篇文章主要介紹了Java并發(fā)編程Callable與Future的應(yīng)用實例代碼,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • SpringMVC攔截器——實現(xiàn)登錄驗證攔截器的示例代碼

    SpringMVC攔截器——實現(xiàn)登錄驗證攔截器的示例代碼

    本篇文章主要介紹了SpringMVC攔截器——實現(xiàn)登錄驗證攔截器的示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-02-02
  • Java中的線程ThreadLocal詳細(xì)解析

    Java中的線程ThreadLocal詳細(xì)解析

    這篇文章主要介紹了Java中的線程ThreadLocal詳細(xì)解析,ThreadLocal是線程本地變量,存儲在ThreadLocal里面的數(shù)據(jù)都是線程安全的,一般ThreadLocal適用的場景多是各個線程間沒有變量共享需要的同步問題場景,需要的朋友可以參考下
    2023-10-10
  • Java多例設(shè)計模式實例詳解

    Java多例設(shè)計模式實例詳解

    這篇文章主要介紹了Java多例設(shè)計模式,結(jié)合實例形式分析了基于Java的多例模式概念、原理、定義與使用方法,需要的朋友可以參考下
    2018-05-05
  • SpringBoot自定義雪花算法生成ID的實現(xiàn)示例

    SpringBoot自定義雪花算法生成ID的實現(xiàn)示例

    雪花算法是一種生成唯一ID的分布式算法,它能生成不重復(fù)的、有時間順序的全局唯一ID,本文主要介紹了SpringBoot自定義雪花算法生成ID的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下
    2025-04-04
  • 詳解Java中-classpath和路徑的使用

    詳解Java中-classpath和路徑的使用

    本篇文章主要介紹了Java中-classpath和路徑的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • Java中使用BigDecimal進(jìn)行精確運算

    Java中使用BigDecimal進(jìn)行精確運算

    這篇文章主要介紹了Java中使用BigDecimal進(jìn)行精確運算的方法,非常不錯,需要的朋友參考下
    2017-02-02

最新評論

达州市| 五大连池市| 华亭县| 依安县| 芦溪县| 通榆县| 栾城县| 修武县| 封开县| 拉萨市| 乌兰察布市| 来安县| 开鲁县| 山丹县| 桐柏县| 华安县| 隆林| 迭部县| 沙湾县| 全椒县| 青海省| 沙洋县| 马边| 靖安县| 岗巴县| 昭平县| 来安县| 平武县| 稷山县| 青岛市| 湄潭县| 呼伦贝尔市| 乐山市| 保亭| 九台市| 祁阳县| 莎车县| 江北区| 扶绥县| 白水县| 丰城市|