【SpringCloud教程】8.SpringCloud Alibaba服务保护Sentinel代码控制限流

前言

上篇讲到了Sentinel 简单使用和Sentinel dashboard 控制台整合,这篇主要讲到通过注解和自定义编码来实现限流。

Sentinel 服务保护配置类

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * Sentinel服务保护配置
 * @author terry
 * @version 1.0
 * @date 2022/5/22 15:31
 */
@Configuration
public class SentinelConfig {

    @PostConstruct
    public void init() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule1 = new FlowRule();
        rule1.setResource("userQps");
        // QPS控制在1,每秒钟运行1个请求
        rule1.setCount(1);
        // QPS限流
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setLimitApp("default");
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
    }
}

通过注解实现限流

@SentinelResource 对应 配置类的resource,代码如下:

public String qpsException(BlockException e) {
    e.printStackTrace();
    return "当前访问人数过多,稍后重试!";
}

@GetMapping("testAnnotation")
@SentinelResource(value = "userQps", blockHandler = "qpsException")
public String testAnnotation() throws InterruptedException {
    Thread.sleep(1000);
    return "terry";
}

image-20220522153942284

被限流后:

image-20220522154020640

通过代码整合限流


    public String qpsException(BlockException e) {
        e.printStackTrace();
        return "当前访问人数过多,稍后重试!";
    }

    @RequestMapping("/testCode")
    public String orderToMember() {
        Entry entry = null;
        try {
            entry = SphU.entry("userQps");
            return "terry";
        } catch (BlockException e) {
            // 限流的情况就会进入到Exception
            return qpsException(e);
        } finally {
            // 避免调用链记录异常
            if (entry != null) {
                entry.exit();
            }
        }
    }

测试:

image-20220522154728860

被限流后:

image-20220522154713905

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

terrybg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值