sentinel注解配置

2021-08-10  本文已影响0人  板栗炖牛肉

前言

解决方案

        <!-- sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2021.1</version>
        </dependency>
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

        <!-- sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2021.1</version>
        </dependency>
       <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
   <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>7.0.1.Final</version>
        </dependency>
spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:30010
        heartbeat-interval-ms: 1000
      enabled: true

@Configuration
public class CustomBlockHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String msg = null;
        if (e instanceof FlowException) {
            //限流
            msg = JSON.toJSONString(new RestBean<>(RestCodeType.BUSY_BUSINESS));
        } else if (e instanceof DegradeException) {
            //BUSY_TOO_MANY_PEOPLE
            msg = JSON.toJSONString(new RestBean<>(RestCodeType.BUSY_UNREACHABLE));
        } else if (e instanceof ParamFlowException) {
            //热点参数限流
            msg = JSON.toJSONString(new RestBean<>(RestCodeType.BUSY_BUSINESS));
        } else if (e instanceof SystemBlockException) {
            //系统规则
            msg = JSON.toJSONString(new RestBean<>(RestCodeType.BUSY_UNREACHABLE));
        } else if (e instanceof AuthorityException) {
            //授权规则
            msg = JSON.toJSONString(new RestBean<>(RestCodeType.BUSY_UNREACHABLE));
        }
        response.setStatus(400);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.getWriter().write(msg);
        response.getWriter().close();
    }

}

public abstract class CustomSentinelConfig {

    @PostConstruct
    private void config() {
        List<FlowRule> flowRules = new ArrayList<>();

        /**
         * 添加限流方式
         * 10次拒绝访问
         */
        FlowRule flowRule1 = new FlowRule();
        //资源名,资源名是限流规则的作用对象
        flowRule1.setResource("限流-10");
        //限流阈值
        flowRule1.setCount(10);
        //调用关系限流策略:直接、链路、关联
        flowRule1.setStrategy(0);
        //限流阈值类型,QPS 或线程数模式
        flowRule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //流控效果(直接拒绝 / 慢启动模式 / 排队等待),不支持按调用关系限流
        flowRule1.setControlBehavior(0);

        /**
         * 添加限流方式
         * 5次等待排队
         */
        FlowRule flowRule2 = new FlowRule();
        //资源名,资源名是限流规则的作用对象
        flowRule2.setResource("限流等待-5");
        //限流阈值
        flowRule2.setCount(5);
        //调用关系限流策略:直接、链路、关联
        flowRule2.setStrategy(0);
        //限流阈值类型,QPS 或线程数模式
        flowRule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //流控效果(直接拒绝 / 慢启动模式 / 排队等待),不支持按调用关系限流
        flowRule2.setControlBehavior(2);
        //超时时间设置
        flowRule2.setMaxQueueingTimeMs(60000);

        /**
         * 添加限流方式
         * 2次拒绝访问
         */
        FlowRule flowRule3 = new FlowRule();
        //资源名,资源名是限流规则的作用对象
        flowRule3.setResource("限流-2");
        //限流阈值
        flowRule3.setCount(2);
        //调用关系限流策略:直接、链路、关联
        flowRule3.setStrategy(0);
        //限流阈值类型,QPS 或线程数模式
        flowRule3.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //流控效果(直接拒绝 / 慢启动模式 / 排队等待),不支持按调用关系限流
        flowRule3.setControlBehavior(0);

        /**
         * 添加限流方式
         * 10次等待排队
         */
        FlowRule flowRule4 = new FlowRule();
        //资源名,资源名是限流规则的作用对象
        flowRule4.setResource("限流等待-10");
        //限流阈值
        flowRule4.setCount(10);
        //调用关系限流策略:直接、链路、关联
        flowRule4.setStrategy(0);
        //限流阈值类型,QPS 或线程数模式
        flowRule4.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //流控效果(直接拒绝 / 慢启动模式 / 排队等待),不支持按调用关系限流
        flowRule4.setControlBehavior(2);
        //超时时间设置
        flowRule4.setMaxQueueingTimeMs(60000);

        /**
         * 添加限流方式
         * 线程最多五个
         */
        FlowRule flowRule5 = new FlowRule();
        //资源名,资源名是限流规则的作用对象
        flowRule5.setResource("线程-5");
        //限流阈值
        flowRule5.setCount(5);
        //调用关系限流策略:直接、链路、关联
        flowRule5.setStrategy(0);
        //限流阈值类型,QPS 或线程数模式
        flowRule5.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        //流控效果(直接拒绝 / 慢启动模式 / 排队等待),不支持按调用关系限流
        flowRule5.setControlBehavior(0);
        //超时时间设置
        flowRule5.setMaxQueueingTimeMs(60000);


        /**
         * 组装限流
         */
        flowRules.add(flowRule1);
        flowRules.add(flowRule2);
        flowRules.add(flowRule3);
        flowRules.add(flowRule4);
        flowRules.add(flowRule5);
        FlowRuleManager.loadRules(currentLimitRules(flowRules));
    }

    /**
     * 限流规则配置
     *
     * @param rules
     * @return
     */
    protected abstract List<FlowRule> currentLimitRules(List<FlowRule> rules);

}
@Configuration
public class SentinelConfig extends CustomSentinelConfig {

    @Override
    protected List<FlowRule> currentLimitRules(List<FlowRule> rules) {
        return rules;
    }
}

@RestController
public class SentinelController {
    @SentinelResource(value = "线程-5")
    @RequestMapping(value = "/ss")
    public String ss(String id, HttpServletResponse response) throws Exception {
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "访问结果";
    }
}
@RestController
public class SentinelController {

    @SentinelResource(value = "线程-5",blockHandler = "ssHandler")
    @RequestMapping(value = "/ss")
    public String ss(String id, HttpServletResponse response) throws Exception {
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "访问结果";
    }
    
    public String ssHandler(String id, HttpServletResponse response, BlockException b) throws Exception {
        return "错误代码";
    }

}
    @SentinelResource(value = "线程-5")
  public String ss(String id, HttpServletResponse response) throws Exception {
...
 else if (msg.contains("FlowException")) {
            logger.error("全局异常捕获,限流开始", "FlowException");
            restBean.setType(RestCodeType.BUSY_BUSINESS, e);
        } 
...
image.png image.png image.png image.png image.png 自定义Handler捕获 正常结果时间 网页访问时间
image.png

结尾

上一篇下一篇

猜你喜欢

热点阅读