@SentinelRestTemplate使用

本文介绍了如何在Spring Boot应用中使用Sentinel与RestTemplate集成,通过注解配置实现服务间的流量控制和熔断处理。详细步骤包括:为RestTemplate添加Sentinel注解,编写BlockHandler来处理限流和熔断异常,配置yml开关以启用或禁用该功能,并提供了一个测试用例展示其工作流程。
摘要由CSDN通过智能技术生成


一、给RestTemplate加注解

    @Bean
    @LoadBalanced
    @SentinelRestTemplate(
            blockHandler = "handleBlock",
            fallback = "handleFallback",
            fallbackClass = SentinelBlockHandler.class,
            blockHandlerClass = SentinelBlockHandler.class)
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

二、写异常Handler:SentinelBlockHandler

ClientHttpResponseImpl 是ClientHttpResponse的实现类,自己可以写。


import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;


@Slf4j
public class SentinelBlockHandler {

    //限流熔断业务逻辑
    public static ClientHttpResponse handleBlock(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
        log.info("handleBlock");
        return new  ClientHttpResponseImpl();
    }


    //异常熔断业务逻辑
    public static  ClientHttpResponse handleFallback(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
        log.info("handleFallback");
        return new ClientHttpResponseImpl();
    }

}

三.yml写个开关

resttemplate:
  sentinel: #@SentinelRestTemplate 开启、关闭
    enabled: true

四.测试

    @GetMapping("/testSentinelRestTemplate/{userId}")
    public String testSentinelRestTemplate(@PathVariable Integer userId){
        UserDTO userDTO = restTemplate.getForObject("http://user-center/users/{userId}",UserDTO.class,userId);
        return userDTO.toString();
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值