Sentinel限流

1、注意版本(springboot的版本要和sentinel的版本适配)
 

<dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        <version>2021.0.6.0</version>
</dependency>

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.15</version>

2、如果报错循环依赖

spring:
        cloud:
                sentinel:
                        filter:
                                enabled: false // 解决循环依赖报错
                        transport:
                                port: 8719
                        dashboard: localhost:8080

3、限流规则

public static void main(String[] args) {
        try {
            SpringApplication.run(PsychologyApplication.class, args);
            initSentinel();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 定义限流规则
     */
    private static void initSentinel() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("hello"); // 资源名称,限流接口注解中的value
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 根据 QPS 限流
        rule.setCount(1); // QPS 阈值【每秒只允许通过一个请求】
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT); // 调用关系限流策略【非必须设置】
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 流控效果【非必须设置】
        rule.setClusterMode(false); // 是否集群限流【非必须设置,默认非集群】
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

4、限流接口

@GetMapping(value = "/hello/{name}")
    @SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
    public String apiHello(@PathVariable String name) {
        return "hello";
    }

    // Fallback 函数,函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String helloFallback(String s) {
        return String.format("Halooooo %s", s);
    }

    // Block 异常处理函数,参数最后多一个 BlockException,其余与原函数一致.
    public String exceptionHandler(String s, BlockException ex) {
        // Do some log here.
        ex.printStackTrace();
        return "Oops, error occurred at " + s;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值