SpringCloud 中 Sentinel 的基本使用
-
依赖
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> <version>2.2.6.RELEASE</version> </dependency>
-
配置限流规则
@PostConstruct private static void initFlowRules(){ List<FlowRule> rules = new ArrayList<>(); FlowRule rule = new FlowRule(); //令牌 rule.setResource("key"); //限流方式 rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 设置QPS rule.setCount(1); rules.add(rule); FlowRuleManager.loadRules(rules); }
-
Service
@Service public class SentinelTestService { @SentinelResource(value = "key",blockHandler = "failMethod") public String getData(){ return "获取到数据"; } public String failMethod(BlockException blockException){ return "降级..."; } }
-
Controller
@RestController public class SentinelTestController { @Autowired private SentinelTestService sentinelTestService; @GetMapping(path = "/test") public String test(){ String data = sentinelTestService.getData(); System.out.println(data); return data; } }