1、注意版本(springboot的版本要和sentinel的版本适配)
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2021.0.6.0</version>
</dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.15</version>
2、如果报错循环依赖
spring:
cloud:
sentinel:
filter:
enabled: false // 解决循环依赖报错
transport:
port: 8719
dashboard: localhost:8080
3、限流规则
public static void main(String[] args) {
try {
SpringApplication.run(PsychologyApplication.class, args);
initSentinel();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 定义限流规则
*/
private static void initSentinel() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("hello"); // 资源名称,限流接口注解中的value
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 根据 QPS 限流
rule.setCount(1); // QPS 阈值【每秒只允许通过一个请求】
rule.setStrategy(RuleConstant.STRATEGY_DIRECT); // 调用关系限流策略【非必须设置】
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 流控效果【非必须设置】
rule.setClusterMode(false); // 是否集群限流【非必须设置,默认非集群】
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
4、限流接口
@GetMapping(value = "/hello/{name}")
@SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
public String apiHello(@PathVariable String name) {
return "hello";
}
// Fallback 函数,函数签名与原函数一致或加一个 Throwable 类型的参数.
public String helloFallback(String s) {
return String.format("Halooooo %s", s);
}
// Block 异常处理函数,参数最后多一个 BlockException,其余与原函数一致.
public String exceptionHandler(String s, BlockException ex) {
// Do some log here.
ex.printStackTrace();
return "Oops, error occurred at " + s;
}