sentinel入门案例

1、新建一个springWeb项目

2、引入sentinel核心依赖

<!--sentinel核心依赖-->
<dependency>
      <groupId>com.alibaba.csp</groupId>
      <artifactId>sentinel-core</artifactId>
      <version>1.7.2</version>
</dependency>

3、创建一个controller

4、定义限流规则,并使用Sphu.entry("资源名")的方式使用限流规则

限流规则的定义如下:

1、创建存放限流规则集合
2、创建限流规则
3、定义资源,表示sentinel会对哪个资源生效,定义限流规则类型,RuleCOnstant,Flow_GRAND——QPS:QPS限流类型,定义QPS每秒能通过请求个数
rule.setCount(2);
4、将限流规则存放到集合中
5、加载限流规则
@RestController
public class TestController {
    @GetMapping("hello")
    public String hello(){
        //使用限流规则
        try(Entry entry = SphU.entry("Hello")) {
            return "hello sentinel";
        } catch (BlockException e) {
            e.printStackTrace();
            return "系统繁忙";
        }
    }

    //定义限流规则
    @PostConstruct
    public void initFlowRules(){
        //1、创建存放限流规则集合
        List<FlowRule> rules = new ArrayList<>();
        //2、创建限流规则
        FlowRule rule = new FlowRule();
        //定义资源,表示sentinel会对哪个资源生效
        rule.setResource("Hello");
        //定义限流规则类型,RuleCOnstant,Flow_GRAND——QPS:QPS限流类型
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //定义QPS每秒能通过请求个数
        rule.setCount(2);
        //3、将限流规则存放到集合中
        rules.add(rule);
        //4、加载限流规则
        FlowRuleManager.loadRules(rules);
    }
}

5、引入本地应用接入sentinel本地控制台的依赖

    <!--本地应用接入sentinel本地控制台的依赖-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>1.7.2</version>
        </dependency>

6、启动本地sentinel控制台,sentinel的下载地址:https://github.com/alibaba/Sentinel/releases

启动命令:java -Dserver.port=9000 -jar sentinel-dashboard-1.8.3.jar

7、设置jvm启动参数,将本地应用链接到sentinel-dashboard,启动参数如下

设置sentinel控制台的主机地址和端口:-Dcsp.sentinel.dashboard.server=localhost:9000

设置本地应用在控制台的名称:-Dproject.name=SentinelPrimary

最终效果:

当每秒的请求数量大于2的时候就会被限流

猜你喜欢

转载自blog.csdn.net/weixin_38829588/article/details/123610109