Spring Cloud 整合Sentinel
Spring Cloud 整合 Alibaba Sentinel 主要涉及以下几个步骤:
- 引入 Sentinel 依赖
- 配置 Sentinel 控制台信息
- 配置 Sentinel 的限流规则
- 使用注解定义需要保护的资源
- 使用 Sentinel 提供的 API 进行编程式限流
以下是一个简单的示例,展示如何在 Spring Cloud 应用中整合 Sentinel:
1. 在 pom.xml 中添加 Sentinel 依赖
<dependencies>
<!-- Sentinel 依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
</dependencies>
2. application.yml 配置文件中添加 Sentinel 控制台信息
spring:
cloud:
sentinel:
transport:
dashboard: 127.0.0.1:8080 # Sentinel 控制台地址
port: 8719 # 默认端口,若冲突需更改
3. 配置限流规则
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
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 java.util.ArrayList;
import java.util.List;
public class SentinelConfiguration {
public SentinelConfiguration() {
initFlowRules();
}
private void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("myResource"); // 需要限流的资源名
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流规则为每秒的请求量
rule.setCount(1); // 限制为每秒1次请求
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
4. 使用注解定义资源
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test")
@SentinelResource(value = "myResource", blockHandler = "handleException")
public String test() {
return "Hello Sentinel";
}
public String handleException(BlockException ex) {
return "Too many requests";
}
}
5. 编程式限流
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant
评论已关闭