天天看点

Sentinel Apache Httpclient 适配器介绍

添加以下依赖项

pom.xml

(如果您使用的是 Maven):

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-apache-httpclient-adapter</artifactId>
    <version>x.y.z</version>
</dependency>      

我们可以在初始化

SentinelApacheHttpClientBuilder

时使用when

CloseableHttpClient

,例如:

CloseableHttpClient httpclient = new SentinelApacheHttpClientBuilder().build();      

如果我们要添加一些额外的配置,可以参考下面的代码

HttpClientBuilder builder = new SentinelApacheHttpClientBuilder();
//builder Other Definitions
CloseableHttpClient httpclient = builder.build();      

配置

  • SentinelApacheHttpClientConfig

    配置:
名称 描述 类型 默认值
字首 自定义资源前缀

String

httpclient:

提取器 自定义资源提取器

ApacheHttpClientResourceExtractor

DefaultApacheHttpClientResourceExtractor

倒退 当请求被阻塞时处理请求

ApacheHttpClientFallback

DefaultApacheHttpClientFallback

提取器(资源提取器)

我们可以在默认配置中定义

ApacheHttpClientResourceExtractor

自定义资源提取器替换,例如: httpclient:GET:/httpclient/back/1 ==> httpclient:GET:/httpclient/back/{id}

DefaultApacheHttpClientResourceExtractor

SentinelApacheHttpClientBuilder

SentinelApacheHttpClientConfig config = new SentinelApacheHttpClientConfig();
config.setExtractor(new ApacheHttpClientResourceExtractor() {

    @Override
    public String extractor(HttpRequestWrapper request) {
        String contains = "/httpclient/back/";
        String uri = request.getRequestLine().getUri();
        if (uri.startsWith(contains)) {
            uri = uri.substring(0, uri.indexOf(contains) + contains.length()) + "{id}";
        }
        return request.getMethod() + ":" + uri;
    }
});
CloseableHttpClient httpclient = new SentinelApacheHttpClientBuilder(config).build();      

回退(块处理)

我们可以

ApacheHttpClientFallback

SentinelApacheHttpClientBuilder

默认配置中定义,根据实际场景来处理请求被阻塞,例如:

public class DefaultApacheHttpClientFallback implements ApacheHttpClientFallback {

    @Override
    public CloseableHttpResponse handle(HttpRequestWrapper request, BlockException e) {
        // Just wrap and throw the exception.
        throw new SentinelRpcException(e);
    }
}