zumengjie

 降级

控制台

熔断规则

流控规则

授权规则

热点规则

系统规则

持久化到nacos

降级

方法级别降级

api这个服务通过openFeign调用business,但是business这个服务没有启动,会报错,然后走的是降级方法。

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController
public class DemoController {
    @Autowired
    private BusinessService businessService;

    @SentinelResource(fallback = "demo1Fallback")
    @GetMapping(value = "demo1")
    public String demo1(){
        businessService.demo1();
        return "";
    }

    public String demo1Fallback(){
        return "方法降级~~~~~~~~~~~~";
    }
}
View Code

类级别降级

需要创建降级类,在需要降级的方法上声明降级类和降级方法。

package com.datang.api.controller;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 16:03
 **/
public class DemoControllerFallBack {
    public static String demo1Fallback(){
        return "类降级~~~~~~~~~~~~";
    }
}
View Code
package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController
public class DemoController {
    @Autowired
    private BusinessService businessService;

    @SentinelResource(fallback = "demo1Fallback",fallbackClass = DemoControllerFallBack.class)
    @GetMapping(value = "demo1")
    public String demo1(){
        return businessService.demo1();
    }
}
View Code

控制台

https://github.com/alibaba/Sentinel/releases 下载控制台

启动jar包命令

java -Dserver.port=8888 -Dcsp.sentinel.dashboard.server=localhost:8888 -Dproject.name=sentinel-dashboard -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboard.auth.password=111 -jar sentinel-dashboard-1.8.4.jar

工程配置,sentinel.transport.dashboard 控制台地址 sentinel.transport.port 监控服务端口 sentinel.eager 项目启动就注册到控制台

server:
  port: 8080
spring:
  application:
    name: api
  cloud:
    nacos:
      discovery:
        server-addr: 127.00.1:8848
    sentinel:
      transport:
        dashboard: localhost:8888
        port: 8720
      eager: true
View Code

熔断规则

慢调用比例

1000毫秒内10个请求中有50%的请求相应时间超过500毫秒则熔断10秒钟。

 

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController
public class DemoController {
    @Autowired
    private BusinessService businessService;

    @SentinelResource(value = "slowRequest", fallback = "demo1Fallback")
    @GetMapping(value = "demo1")
    public String demo1() {
        try {
            Thread.sleep(1000);
        }catch (Exception e){}
        return "success";
    }

    public  String demo1Fallback(){
        return "方法降级~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule(){
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule slowRequest = ApiServer.slowRequest();
        rules.add(slowRequest);
        DegradeRuleManager.loadRules(rules);
    }

    //慢调用比例
    public static DegradeRule slowRequest(){
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest2");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }
}
View Code

异常比例

1000毫秒内10个请求50%抛出异常则熔断10秒。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController
public class DemoController {
    @Autowired
    private BusinessService businessService;

    @SentinelResource(value = "errorRatio", fallback = "demo1Fallback")
    @GetMapping(value = "demo1")
    public String demo1() {
        System.out.println("正常请求");
        int i = 1/0;
        return "success";
    }

    public  String demo1Fallback(){
        return "方法降级~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule(){
        List<DegradeRule> rules = new ArrayList<>();
        rules.add(ApiServer.slowRequest());
        rules.add(ApiServer.errorRatio());
        DegradeRuleManager.loadRules(rules);
    }

    //慢调用比例
    public static DegradeRule slowRequest(){
        DegradeRule rule = new DegradeRule();
        rule.setResource("RuleConstant");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }
    //异常比例
    public static DegradeRule errorRatio(){
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }
}
View Code

异常数

1000毫秒内10个请求中5个抛出异常则熔断10秒。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController
public class DemoController {
    @Autowired
    private BusinessService businessService;

    @SentinelResource(value = "errorCount", fallback = "demo1Fallback")
    @GetMapping(value = "demo1")
    public String demo1() {
        System.out.println("正常请求");
        int i = 1/0;
        return "success";
    }

    public  String demo1Fallback(){
        return "方法降级~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule(){
        List<DegradeRule> rules = new ArrayList<>();
        rules.add(ApiServer.slowRequest());
        rules.add(ApiServer.errorRatio());
        rules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(rules);
    }

    //慢调用比例
    public static DegradeRule slowRequest(){
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }
    //异常比例
    public static DegradeRule errorRatio(){
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }
    //异常数
    public static DegradeRule errorCount(){
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }
}
View Code

流控规则

QPS-直接-快速失败

对qps这个资源做QPS阈值类型限流,针对来源为default(全部来源,稍后会介绍来源)1秒只能访问1次流控模式是直接,直接就是不牵扯其他的资源,流控效果是快速失败,也就是直接走限流的回调。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;


    @GetMapping(value = "demo1")
    @SentinelResource(value = "qps", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        FlowRuleManager.loadRules(flowRules);
    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("aaa");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(10);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }
}
View Code

 

来源应用

来源应用指的是对接口访问者进行身份鉴定。需要先在代码中设定一个token,然后通过传递参数方式将token和value传入。

package com.datang.api.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/3 17:27
 **/
@Component
public class TokenRequestOriginParser implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest httpServletRequest) {
        String authority = httpServletRequest.getParameter("auth");
        return authority;
    }
}
View Code

以上的设置需要来源为aaa,我们可以在参数添加auth=aaa这样流控规则才可以生效。

如果不设置auth或者auth的value不是aaa,则流控规则不会生效,默认的流控规则是default针对所有来源。

QPS-直接-Warm Up

Warm Up模式应对突如其来的高并发,当并发来临时并不会立刻将单机阈值直接拉到最高,而是预热一段时间后单机阈值才会到达预设值的。以下设置3QPS其实真正能做到3QPS需要等到8秒预热后。8秒预热前大概是1QPS-2QPS。

 

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;


    @GetMapping(value = "demo1")
    @SentinelResource(value = "qpsDirectConnectionWarmUp", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code

 使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        FlowRuleManager.loadRules(flowRules);
    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("aaa");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }
}
View Code

 

QPS-直接-排队等待

当QPS超过阈值后,不会立刻限流而是等待一段时间。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;


    @GetMapping(value = "demo1")
    @SentinelResource(value = "qpsDirectConnectionQueueUp", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        flowRules.add(ApiServer.qpsDirectConnectionQueueUp());
        FlowRuleManager.loadRules(flowRules);
    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("aaa");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }

    //QPS-直接-排队等待
    public static FlowRule qpsDirectConnectionQueueUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionQueueUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(3);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);//流控效果
        rule.setMaxQueueingTimeMs(300);//超时时间
        return rule;
    }
}
View Code

QPS-关联-快速失败

当关联资源B并发量超过单机阈值后,关联资源B不会限流但资源A会被限流。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;


    @GetMapping(value = "demo1")
    @SentinelResource(value = "qpsCorrelationFailFast", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        return "success";
    }


    @GetMapping(value = "demo2")
    @SentinelResource(value = "qpsCorrelationFailFast2", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo2() {
        return "success";
    }


    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        flowRules.add(ApiServer.qpsDirectConnectionQueueUp());
        flowRules.add(ApiServer.qpsCorrelationFailFast());
        FlowRuleManager.loadRules(flowRules);
    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }

    //QPS-直接-排队等待
    public static FlowRule qpsDirectConnectionQueueUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionQueueUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(3);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);//流控效果
        rule.setMaxQueueingTimeMs(300);//超时时间
        return rule;
    }

    //QPS-关联-快速失败
    public static FlowRule qpsCorrelationFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsCorrelationFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_RELATE);//流控模式
        rule.setRefResource("qpsCorrelationFailFast2");//关联资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }
}
View Code

QPS-链路-快速失败

只有从A入口访问B才会触发限流,而从其他的入口则不会触发。yml中需要配置 web-context-unify: false 被限流的资源不能在Controler里,只能在Service中。

server:
  port: 8080
spring:
  application:
    name: api
  cloud:
    nacos:
      discovery:
        server-addr: 127.00.1:8848
    sentinel:
      transport:
        dashboard: localhost:8888
        port: 8720
      eager: true
      web-context-unify: false
ribbon:
  ReadTimeout: 5000
  ConnectTimeout: 5000
feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
eureka:
    client:
      register-with-eureka: true
      fetch-registry: true
      service-url:
        defaultZone: http://localhost:7001/eureka
View Code
package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import com.datang.api.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;


    @Autowired
    private DemoService service;

    @GetMapping(value = "/demo2")
    public String demo2() {
        System.out.println("demo2!!!!!!!!!!");
        return service.demo1();
    }

    @GetMapping(value = "/demo3")
    public String demo3() {
        System.out.println("demo3!!!!!!!!!!");
        return service.demo1();
    }


}
View Code
package com.datang.api.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/5 17:00
 **/
@Service
public class DemoService {

    @SentinelResource(value = "qpsLikeFailFast", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

并发线程数-链路-快速失败

threadDirectConnectionFailFast资源只能有5个线程并发访问。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;

    @GetMapping(value = "demo1")
    @SentinelResource(value = "threadDirectConnectionFailFast", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        try {
            Thread.sleep(1000*10);
        }catch (Exception e){}
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());

        DegradeRuleManager.loadRules(degradeRules);

        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        flowRules.add(ApiServer.qpsDirectConnectionQueueUp());
        flowRules.add(ApiServer.qpsCorrelationFailFast());
        flowRules.add(ApiServer.qpsLikeFailFast());
        flowRules.add(ApiServer.threadDirectConnectionFailFast());

        FlowRuleManager.loadRules(flowRules);
    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }

    //QPS-直接-排队等待
    public static FlowRule qpsDirectConnectionQueueUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionQueueUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(3);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);//流控效果
        rule.setMaxQueueingTimeMs(300);//超时时间
        return rule;
    }

    //QPS-关联-快速失败
    public static FlowRule qpsCorrelationFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsCorrelationFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_RELATE);//流控模式
        rule.setRefResource("qpsCorrelationFailFast2");//关联资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-链路-快速失败
    public static FlowRule qpsLikeFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsLikeFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);//流控模式
        rule.setRefResource("/demo2");//入口资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //并发线程数-直接-快速失败
    public static FlowRule threadDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("threadDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }
}
View Code

授权规则

白名单

只有访问来源是 a 的才能访问该资源,同样需要实现 RequestOriginParser 接口,在流控规则中我们是从参数中获取token,这次我们从head中获取,同样的如果访问来源没有带token是无法触发授权规则的。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;

    @GetMapping(value = "demo1")
    @SentinelResource(value = "whiteList", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code
package com.datang.api.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/3 17:27
 **/
@Component
public class TokenRequestOriginParser implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest httpServletRequest) {
        String authority = httpServletRequest.getHeader("auth");
        return authority;
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        flowRules.add(ApiServer.qpsDirectConnectionQueueUp());
        flowRules.add(ApiServer.qpsCorrelationFailFast());
        flowRules.add(ApiServer.qpsLikeFailFast());
        flowRules.add(ApiServer.threadDirectConnectionFailFast());
        FlowRuleManager.loadRules(flowRules);

        List<AuthorityRule> authorityRules = new ArrayList<>();
        authorityRules.add(ApiServer.whiteList());
        AuthorityRuleManager.loadRules(authorityRules);

    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }

    //QPS-直接-排队等待
    public static FlowRule qpsDirectConnectionQueueUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionQueueUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(3);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);//流控效果
        rule.setMaxQueueingTimeMs(300);//超时时间
        return rule;
    }

    //QPS-关联-快速失败
    public static FlowRule qpsCorrelationFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsCorrelationFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_RELATE);//流控模式
        rule.setRefResource("qpsCorrelationFailFast2");//关联资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-链路-快速失败
    public static FlowRule qpsLikeFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsLikeFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);//流控模式
        rule.setRefResource("/demo2");//入口资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //并发线程数-直接-快速失败
    public static FlowRule threadDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("threadDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //白名单
    private static AuthorityRule whiteList(){
        AuthorityRule rule = new AuthorityRule();
        rule.setResource("whiteList");//资源名,即规则的作用对象
        rule.setLimitApp("a");//流控应用
        rule.setStrategy(RuleConstant.AUTHORITY_WHITE);//授权类型
        return rule;
    }

   
}
View Code

黑名单

如果访问来源是 b 则触发黑名单,其他的访问来源则不会限制。同样需要实现 RequestOriginParser 接口,同样的如果访问来源没有带token是无法触发授权规则的。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;

    @GetMapping(value = "demo1")
    @SentinelResource(value = "blackList", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1() {
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code
package com.datang.api.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/3 17:27
 **/
@Component
public class TokenRequestOriginParser implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest httpServletRequest) {
        String authority = httpServletRequest.getHeader("auth");
        return authority;
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        flowRules.add(ApiServer.qpsDirectConnectionQueueUp());
        flowRules.add(ApiServer.qpsCorrelationFailFast());
        flowRules.add(ApiServer.qpsLikeFailFast());
        flowRules.add(ApiServer.threadDirectConnectionFailFast());
        FlowRuleManager.loadRules(flowRules);

        List<AuthorityRule> authorityRules = new ArrayList<>();
        authorityRules.add(ApiServer.blackList());
        authorityRules.add(ApiServer.whiteList());
        AuthorityRuleManager.loadRules(authorityRules);

    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }

    //QPS-直接-排队等待
    public static FlowRule qpsDirectConnectionQueueUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionQueueUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(3);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);//流控效果
        rule.setMaxQueueingTimeMs(300);//超时时间
        return rule;
    }

    //QPS-关联-快速失败
    public static FlowRule qpsCorrelationFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsCorrelationFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_RELATE);//流控模式
        rule.setRefResource("qpsCorrelationFailFast2");//关联资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-链路-快速失败
    public static FlowRule qpsLikeFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsLikeFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);//流控模式
        rule.setRefResource("/demo2");//入口资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //并发线程数-直接-快速失败
    public static FlowRule threadDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("threadDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //白名单
    private static AuthorityRule whiteList(){
        AuthorityRule rule = new AuthorityRule();
        rule.setResource("whiteList");//资源名,即规则的作用对象
        rule.setLimitApp("a");//流控应用
        rule.setStrategy(RuleConstant.AUTHORITY_WHITE);//授权类型
        return rule;
    }

    //黑名单
    private static AuthorityRule blackList(){
        AuthorityRule rule = new AuthorityRule();
        rule.setResource("blackList");//资源名,即规则的作用对象
        rule.setLimitApp("b");//流控应用
        rule.setStrategy(RuleConstant.AUTHORITY_BLACK);//授权类型
        return rule;
    }

}
View Code

热点规则

对资源中的参数做限制,10秒内只允许1QPS,可以对参数的值做额外的限制,值为 zs 的QPS为2。

package com.datang.api.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.datang.api.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2022/7/1 15:48
 **/
@RestController

public class DemoController {
    @Autowired
    private BusinessService businessService;

    @GetMapping(value = "demo1")
    @SentinelResource(value = "param", blockHandler = "demoBlockHandler", fallback = "demoFallback")
    public String demo1(String name) {
        return "success";
    }

    public String demoFallback() {
        return "方法降级~~~~~~~~~~~~";
    }

    public String demoBlockHandler(String name,BlockException e) {
        return "方法限流~~~~~~~~~~~~";
    }
}
View Code

使用API的方式设置

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowItem;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        //流控规则
        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        flowRules.add(ApiServer.qpsDirectConnectionQueueUp());
        flowRules.add(ApiServer.qpsCorrelationFailFast());
        flowRules.add(ApiServer.qpsLikeFailFast());
        flowRules.add(ApiServer.threadDirectConnectionFailFast());
        FlowRuleManager.loadRules(flowRules);

        //授权规则
        List<AuthorityRule> authorityRules = new ArrayList<>();
        authorityRules.add(ApiServer.blackList());
        authorityRules.add(ApiServer.whiteList());
        AuthorityRuleManager.loadRules(authorityRules);

        //热点规则
        List<ParamFlowRule> paramFlowRules = new ArrayList<>();
        paramFlowRules.add(ApiServer.param());
        ParamFlowRuleManager.loadRules(paramFlowRules);
    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }

    //QPS-直接-排队等待
    public static FlowRule qpsDirectConnectionQueueUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionQueueUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(3);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);//流控效果
        rule.setMaxQueueingTimeMs(300);//超时时间
        return rule;
    }

    //QPS-关联-快速失败
    public static FlowRule qpsCorrelationFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsCorrelationFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_RELATE);//流控模式
        rule.setRefResource("qpsCorrelationFailFast2");//关联资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-链路-快速失败
    public static FlowRule qpsLikeFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsLikeFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);//流控模式
        rule.setRefResource("/demo2");//入口资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //并发线程数-直接-快速失败
    public static FlowRule threadDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("threadDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //白名单
    private static AuthorityRule whiteList(){
        AuthorityRule rule = new AuthorityRule();
        rule.setResource("whiteList");//资源名,即规则的作用对象
        rule.setLimitApp("a");//流控应用
        rule.setStrategy(RuleConstant.AUTHORITY_WHITE);//授权类型
        return rule;
    }

    //黑名单
    private static AuthorityRule blackList(){
        AuthorityRule rule = new AuthorityRule();
        rule.setResource("blackList");//资源名,即规则的作用对象
        rule.setLimitApp("b");//流控应用
        rule.setStrategy(RuleConstant.AUTHORITY_BLACK);//授权类型
        return rule;
    }

    //热点规则
    public static ParamFlowRule param(){
        ParamFlowRule rule = new ParamFlowRule();
        rule.setResource("param");//资源名
        rule.setParamIdx(0);//参数索引
        rule.setCount(1);//单机阈值
        rule.setDurationInSec(10);//统计窗口时长

        List<ParamFlowItem> items = new ArrayList<>();
        ParamFlowItem item = new ParamFlowItem();//参数例外项
        item.setClassType(String.class.getName());//参数类型
        item.setObject("zs");//参数值
        item.setCount(3);//限流阈值
        items.add(item);

        rule.setParamFlowItemList(items);
        return rule;
    }

}
View Code

系统规则

Sentinel 系统自适应限流对应用级别入口流量进行整体控制,结合应用的 Load、CPU 使用率、平均 RT、入口 QPS 和入口并发线程数等几个维度的监控指标,通过自适应的流控策略,
让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。由于该限流方式中阈值的设置需要很多系统软硬件相关的数据,而与代码关系
不大,所以这种限流方式一般是由运维来设置的。

package com.datang.api;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowItem;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import org.checkerframework.checker.units.qual.A;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableFeignClients
public class ApiServer {
    public static void main(String[] args) {
        SpringApplication.run(ApiServer.class, args);
        initRule();
    }

    public static void initRule() {
        //熔断规则
        List<DegradeRule> degradeRules = new ArrayList<>();
        degradeRules.add(ApiServer.slowRequest());
        degradeRules.add(ApiServer.errorRatio());
        degradeRules.add(ApiServer.errorCount());
        DegradeRuleManager.loadRules(degradeRules);

        //流控规则
        List<FlowRule> flowRules = new ArrayList<>();
        flowRules.add(ApiServer.qpsDirectConnectionFailFast());
        flowRules.add(ApiServer.qpsDirectConnectionWarmUp());
        flowRules.add(ApiServer.qpsDirectConnectionQueueUp());
        flowRules.add(ApiServer.qpsCorrelationFailFast());
        flowRules.add(ApiServer.qpsLikeFailFast());
        flowRules.add(ApiServer.threadDirectConnectionFailFast());
        FlowRuleManager.loadRules(flowRules);

        //授权规则
        List<AuthorityRule> authorityRules = new ArrayList<>();
        authorityRules.add(ApiServer.blackList());
        authorityRules.add(ApiServer.whiteList());
        AuthorityRuleManager.loadRules(authorityRules);

        //热点规则
        List<ParamFlowRule> paramFlowRules = new ArrayList<>();
        paramFlowRules.add(ApiServer.param());
        ParamFlowRuleManager.loadRules(paramFlowRules);

        //系统规则
        List<SystemRule> systemRules = new ArrayList<>();
        systemRules.add(ApiServer.system());
        SystemRuleManager.loadRules(systemRules);
    }

    //慢调用比例
    public static DegradeRule slowRequest() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("slowRequest");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//慢调用比例
        rule.setCount(1000);//最大RT
        rule.setSlowRatioThreshold(0.5);//比例阈值
        rule.setTimeWindow(5000);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常比例
    public static DegradeRule errorRatio() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorRatio");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);//异常比例
        rule.setCount(0.6);//比例阈值
        rule.setTimeWindow(20);//熔断时长
        rule.setMinRequestAmount(50);//最小请求数
        rule.setStatIntervalMs(3000);//统计时长
        return rule;
    }

    //异常数
    public static DegradeRule errorCount() {
        DegradeRule rule = new DegradeRule();
        rule.setResource("errorCount");//资源名,即规则的作用对象
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);//异常数
        rule.setCount(5);//异常数
        rule.setTimeWindow(10);//熔断时长
        rule.setMinRequestAmount(10);//最小请求数
        rule.setStatIntervalMs(1000);//统计时长
        return rule;
    }

    //QPS-直接-快速失败
    public static FlowRule qpsDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-直接-Warm Up
    public static FlowRule qpsDirectConnectionWarmUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionWarmUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);//流控效果
        rule.setWarmUpPeriodSec(10);//预热时长
        return rule;
    }

    //QPS-直接-排队等待
    public static FlowRule qpsDirectConnectionQueueUp(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsDirectConnectionQueueUp");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(3);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);//流控效果
        rule.setMaxQueueingTimeMs(300);//超时时间
        return rule;
    }

    //QPS-关联-快速失败
    public static FlowRule qpsCorrelationFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsCorrelationFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_RELATE);//流控模式
        rule.setRefResource("qpsCorrelationFailFast2");//关联资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //QPS-链路-快速失败
    public static FlowRule qpsLikeFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("qpsLikeFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阈值类型
        rule.setCount(1);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);//流控模式
        rule.setRefResource("/demo2");//入口资源
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //并发线程数-直接-快速失败
    public static FlowRule threadDirectConnectionFailFast(){
        FlowRule rule = new FlowRule();
        rule.setResource("threadDirectConnectionFailFast");//资源名,即规则的作用对象
        rule.setLimitApp("default");//针对来源
        rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);//阈值类型
        rule.setCount(5);//单机阈值
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        return rule;
    }

    //白名单
    private static AuthorityRule whiteList(){
        AuthorityRule rule = new AuthorityRule();
        rule.setResource("whiteList");//资源名,即规则的作用对象
        rule.setLimitApp("a");//流控应用
        rule.setStrategy(RuleConstant.AUTHORITY_WHITE);//授权类型
        return rule;
    }

    //黑名单
    private static AuthorityRule blackList(){
        AuthorityRule rule = new AuthorityRule();
        rule.setResource("blackList");//资源名,即规则的作用对象
        rule.setLimitApp("b");//流控应用
        rule.setStrategy(RuleConstant.AUTHORITY_BLACK);//授权类型
        return rule;
    }

    //热点规则
    public static ParamFlowRule param(){
        ParamFlowRule rule = new ParamFlowRule();
        rule.setResource("param");//资源名
        rule.setParamIdx(0);//参数索引
        rule.setCount(1);//单机阈值
        rule.setDurationInSec(10);//统计窗口时长

        List<ParamFlowItem> items = new ArrayList<>();
        ParamFlowItem item = new ParamFlowItem();//参数例外项
        item.setClassType(String.class.getName());//参数类型
        item.setObject("zs");//参数值
        item.setCount(3);//限流阈值
        items.add(item);

        rule.setParamFlowItemList(items);
        return rule;
    }

    //系统规则
    public static SystemRule system(){
        SystemRule rule = new SystemRule();
        rule.setHighestSystemLoad(100);//LOAD
        rule.setAvgRt(3);//RT
        rule.setMaxThread(2);//线程数
        rule.setQps(5);//入口 QPS
        rule.setHighestCpuUsage(0.2);//CPU 使用率
        return rule;
    }

}
View Code

系统负载 Load 

该模式仅对 Linux/Unix-like 系统生效。当系统 CPU 最近一分钟的负载量 load1 超过了设置的阈值时会触发系统保护,即对再来的请求进行限流处理。这个阈值就是系统负载容量,
系统容量可以由 maxQps * minRt 估算得出。不过,也可以通过 CPU cores * 2.5 计算出其参考数值。

平均响应时间 RT 

当对当前应用上所有入口流量的平均 RT 达到阈值时触发系统保护,单位是毫秒。 

并发线程数 

当对当前应用的所有入口流量进行处理的所有线程数量达到阈值时触发系统保护。 

入口 QPS

当对当前应用的所有入口流量的总 QPS 达到阈值时触发系统保护。

CPU 使用率

当系统 CPU 使用率超过阈值即触发系统保护(取值范围 0.0-1.0),比较灵敏。 

持久化到nacos

在代码中配置了规则以后,往往我们需要在控制台根据实际情况修改,但在控制台修改后,当项目重启,控制台没有保留我们的配置。所以我们需要可以持久化的配置,sentinel提供了本地文件持久化和nacos持久化,这里我用的nacos持久化。

新增csp包,然后再yml文件中连接nacos。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.datang</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>../api</module>
        <module>../business</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        <dependency>-->
        <!--            <groupId>org.springframework.cloud</groupId>-->
        <!--            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
        <!--        </dependency>-->

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

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

        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>

    </dependencies>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>
View Code
server:
  port: 8080
spring:
  application:
    name: api
  cloud:
    nacos:
      discovery:
        server-addr: 127.00.1:8848
    sentinel:
      transport:
        dashboard: localhost:8888
        port: 8720
      eager: true
      web-context-unify: false
      datasource:
        ds-flow: #任意
          nacos:
            server-addr: localhost:8848 #nacos地址
            dataId: ${spring.application.name}-flow-rules #配置文件Data ID
            data-type: json
            rule-type: flow #流控规则
            #rule-type: degrade #熔断规则
            #rule-type: authority #授权规则
            #rule-type: param-flow #热点规则
            #rule-type: system #系统规则
ribbon:
  ReadTimeout: 5000
  ConnectTimeout: 5000
feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
eureka:
    client:
      register-with-eureka: true
      fetch-registry: true
      service-url:
        defaultZone: http://localhost:7001/eureka

#java -Dserver.port=8888 -Dcsp.sentinel.dashboard.server=localhost:8888 -Dproject.name=sentinel-dashboard -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboard.auth.password=sentinel -jar sentinel-dashboard-1.8.4.jar
View Code

控制台与nacos交互

在nacos配置的规则,在sentinel是不显示的,如果需要返显,需要下载sentinel源码然后改造,目前官方只提供了流控规则的控制台改造案例。

修改1:sentinel-dashboard/pom.xml

修改2:D:\office\sentinel\Sentinel-master\sentinel-dashboard\src\test\java\com\alibaba\csp\sentinel\dashboard\rule文件夹及其4个java文件复制到D:\office\sentinel\Sentinel-master\sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\rule下

修改3:D:\office\sentinel\Sentinel-master\sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\v2\FlowControllerV2.java

修改4:D:\office\sentinel\Sentinel-master\sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\NacosConfig.java

修改5:D:\office\sentinel\Sentinel-master\sentinel-dashboard\src\main\resources\application.properties

修改6:D:\office\sentinel\Sentinel-master\sentinel-dashboard\src\main\webapp\resources\app\scripts\directives\sidebar\sidebar.html

mvn clean package -Dmaven.test.skip=true 重新打包,然后启动。

 

 

分类:

技术点:

相关文章: