Sentinel 和SpringBoot /SpringCloud,apollo的结合

本文介绍了如何将Sentinel与SpringBoot、SpringCloud以及Apollo进行集成。首先,引入了相关依赖包;接着,详细讲述了如何定义资源;然后,说明了如何从Apollo获取 Sentinel 的规则;还涉及了错误处理逻辑的实现;最后,提到了Sentinel控制台配置的 Apollo 集成方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,引入相关包

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-apollo</artifactId>
            <version>1.6.1</version>
        </dependency>

2,定义资源

@SentinelResource(value = "XXX")
    public ResponseObject getList(@RequestHeader(value = "lang", required = false, defaultValue = "EN") Language lang) {
       。。。。。。
    }

3,从apollo获得规则

@Configuration
public class SentinelConfig {
    @Value("${sentinel.defaultCount:2000}")
    private double defaultCount;
    //并发线程数
    @Value("${sentinel.defaultGrade:0}")
    private int defaultGrade;
    //Warm Up
    @Value("${sentinel.controlBehavior:1}")
    private int controlBehavior;
    @PostConstruct
    public void loadRuleManager(){
        // Apollo 的命名空间
        String namespaceName = "application";
        // 限流规则的Key, 在Apollo中用此Key
        String flowRuleKey = "sentinel.flowRules";
        // 限流规则的默认值
        String defaultFlowRules = "[]";
        // 注册数据源
        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ApolloDataSource<>(namespaceName,
                flowRuleKey, defaultFlowRules, source -> {
            JSONArray jsonArray = JSON.parseArray(source);
            JSONArray newJsonArray = jsonArray.stream().map(b -> {
                JSONObject jsonObj = (JSONObject) b;
                jsonObj.put("grade", null == jsonObj.getInteger("grade") ? defaultGrade : jsonObj.getInteger("grade"));
                jsonObj.put("count", null == jsonObj.getDouble("count") ? defaultCount : jsonObj.getDouble("count"));
                jsonObj.put("controlBehavior", null == jsonObj.getInteger("controlBehavior") ? controlBehavior : jsonObj.getInteger("controlBehavior"));
                return jsonObj;
            }).collect(Collectors.toCollection(JSONArray::new));
            List<FlowRule> flowRuleList =  newJsonArray.toJavaList(FlowRule.class);
            return flowRuleList;
        });
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    }
}

4,错误处理逻辑

@ControllerAdvice
@Slf4j
public class XXControllerAdvice {



  

    @ResponseBody
    @ExceptionHandler(value = UndeclaredThrowableException.class)
    @ResponseStatus(HttpStatus.OK)
    public Response errorHandler(UndeclaredThrowableException e) {
        if (e.getCause() instanceof BlockException){
            log.error("BlockException occurred:{}", ((BlockException) e.getCause()).getRule().getResource());
            return Response.error(ResponseCode.FORBIDDEN.getCode(), ResponseCode.FORBIDDEN.getMessageKey());
        }
        log.error("Exception occurred:", e);
        return Response.error(ResponseCode.INTERNAL_ERROR.getCode(), e.getMessage());

    }

}

5,控制台配置,可以放入apllo

spring.cloud.sentinel.eager= true
spring.cloud.sentinel.transport.port= 8720
spring.cloud.sentinel.transport.dashboard= 127.0.0.1:8780
spring.cloud.sentinel.transport.heartbeat-interval-ms= 500
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值