目录
官方文档
5种常见限流算法,Sentinel是通过滑动窗口算法来实现的。参考文章:Sentinel限流实现原理
一,控制台启动
1,下载 sentinel控制台
2,启动控制台
java '-Dserver.port=7777' '-Dcsp.sentinel.dashboard.server=localhost:7777' '-Dproject.name=sentinel-dashboard' -jar .\sentinel-dashboard-1.8.0.jar
其中 -Dserver.port=7777 用于指定 Sentinel 控制台端口为 7777
。
3,访问 http://localhost:7777/ ,账户密码默认为:sentinel
4,若想要查看某个项目的限流数据,则需要在项目中引入 Transport 模块来与 Sentinel 控制台进行通信。
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-transport-simple-http</artifactId> <version>x.y.z</version> </dependency>
二,Api基本调用
1,jar包依赖
<!--sentinel-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.0</version>
</dependency>
2,代码实现
/**
* @author HERO
* @date 2021/1/6
* @project_name springboot-demo
*/
public class SentinelDemo {
private static void doSomething(){
Entry entry = null;
try {
entry = SphU.entry("doSomething");
System.out.println("HELLO WORLD"+System.currentTimeMillis());
} catch (BlockException e) {
e.printStackTrace();
} finally {
if (entry != null) {
entry.exit();
}
}
}
private static void initFlowRules(){
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("doSomething");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(20);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
public static void main(String[] args){
initFlowRules();
while (true) {
doSomething();
}
}
}
三、SpringBoot使用
1,jar包依赖
<!--sentinel-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.0</version>
</dependency>
<!--用于和Sentinel通信-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.0</version>
</dependency>
2,参数配置
JVM参数设置:-Dcsp.sentinel.dashboard.server=localhost:7777
3,代码实现
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
//加载规则
initFlowRules();
SpringApplication.run(SpringbootDemoApplication.class, args);
}
//定义流量控制规则
static void initFlowRules(){
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("sentinelDemoHello");
/**
* RuleConstant.FLOW_GRADE_QPS = 1 通过QPS限制
* RuleConstant.FLOW_GRADE_THREAD = 1 通过线程数限制
*/
//rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(20);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
@RestController()
public class SentinelDemoController {
//@SentinelResource 注解定义资源并配置 blockHandler 和 fallback 函数来进行限流之后的处理。
@SentinelResource("sentinelDemoHello")
@GetMapping("sentinelDemoHello")
public String hello(){
return "SentinelDemoController Hello";
}
}
4,观察控制台
用Jemeter测试: Jmeter笔记(一):基本使用