Sentinel-结合RestTemplate

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sentinel-结合RestTemplate相关的知识,希望对你有一定的参考价值。

依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel</artifactId>
</dependency>

配置注入:

@Bean
@LoadBalanced
// 让 RestTemplate 支持 Sentinel 限流
@SentinelRestTemplate(
    blockHandler = "blockHandlerFunc",
    fallback = "fallbackFunc",
    blockHandlerClass = MyBlockHandlerClass.class
)
public RestTemplate restTemplate(){
    return new RestTemplate();
}

异常处理类:

@Slf4j
public class MyBlockHandlerClass {
    public static String blockHandlerFunc(String a, BlockException e){
        log.warn("限流了",e);
        return "";
    }

    public static String fallbackFunc(String a){
        log.warn("降级了");
        return "";
    }
}

调用:

@Autowired
RestTemplate restTemplate;

this.restTemplate.getForObject("http://user-center/users/{id}", Users.class,article.getId());

配置开关:

resttemplate:
    # 关闭 @SentinelRestTemplate 作用,开发环境可以临时关闭: 降级,限流
    sentinel:
        enabled: false

以上是关于Sentinel-结合RestTemplate的主要内容,如果未能解决你的问题,请参考以下文章

Sentinel对RestTemplate和Feign的适配

Spring Cloud Alibaba Sentinel对RestTemplate的支持

SentinelSentinel整合RestTemplate&openFeign&Dubbo

SentinelSentinel整合RestTemplate&openFeign&Dubbo

SentinelSentinel整合RestTemplate&openFeign&Dubbo

SpringCloud - Spring Cloud Alibaba 之 Sentinel DashBoard ;RestTemplate;OpenFeign