sentinel限流
限流主要是保护应用接口不被大量请求冲击导致服务器内存溢出崩溃
限流主要有两种模式
1.QPS限流:通过每秒钟请求数进行限流,超过阈值就进行限流。
2.并发线程数限流:某资源访问的线程数超过阈值就进行限流。(主要用于针对慢请求,比如某个资源内部开销很大或者调用了第三方服务接口开销很大,长期不释放会一直占用线程,当很多请求访问该资源会导致线程池枯竭,系统崩溃)
限流算法
限流算法主要是令牌桶算法,因此限流节点分为单机模式和集群模式。
集群模式需要制定一个节点作为tokenserver,通过发放token来计算访问量。
单机模式则自身节点作为tokenserver.
限流策略配置方式分为两种
一种是通过sentinel提供的dashborad界面进行配置。
一种是通过代码直接配置。
限流DEMO:
一、引入sentinel依赖
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>
二、标记sentinel资源
/** * 限流测试方法 * @return */ @SentinelResource(value = "testSentinel", blockHandler = "testSentinelBlockHandler") @RequestMapping("/testSentinel") public String testRabbitFanoutProvider() { return "测试限流"; } /* 限流的回调方法 */ public String testSentinelBlockHandler(BlockException exception) { return "限流成功"; }
三、配置限流策略(在spring容器启动后将限流策略注册进FlowRuleManager)
package com.zg.common; 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.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; @Configuration public class ApplicationRun implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("启动容器时调用方法"); //增加限流配置 List<FlowRule> list = new ArrayList<>(); FlowRule rule = new FlowRule(); rule.setResource("testSentinel"); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); rule.setCount(0); //为方便测试设置阈值为0 list.add(rule); FlowRuleManager.loadRules(list); } }
测试
访问被限流的资源http://127.0.0.1:8080/feignService1/testSentinel,成功进入限流回调方法。