java 8及以上的版本的运行环境,支持Spring Cloud。
1.创建maven工程引入Sentinel的依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.3</version>
</dependency>
2.定义规则
通过流量控制规则来指定允许资源通过的请求次数,例如下面的代码定义了资源HelloWord每秒最多只能通过20个请求。
public static void main(String[] args){
initFlowRules();
while (true){
try(Entry entry = SphU.entry("HelloWorld")){
System.out.println("hello word");
}catch (BlockException e){
System.out.println("blocked!");
}
}
}
private static void initFlowRules(){
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("HelloWorld");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// Set limit QPS to 20.
rule.setCount(20);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
查看日志~/logs/csp/${appName}-metrics.log.xxx
里看到下面的输出: