本文目录导读:

我来详细介绍Java Sentinel与常见框架的整合案例。
Spring Boot 整合 Sentinel
Maven依赖配置
<!-- Sentinel 核心依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.6</version>
</dependency>
<!-- Spring Boot 整合 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-boot-starter</artifactId>
<version>1.8.6</version>
</dependency>
<!-- 控制台支持 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.6</version>
</dependency>
配置文件 application.yml
spring:
application:
name: sentinel-demo
cloud:
sentinel:
transport:
dashboard: localhost:8080 # Sentinel控制台地址
port: 8719 # 与Dashboard通信的端口
eager: true # 懒加载改为true,启动即连接控制台
server:
port: 8081
基础使用示例
@RestController
@Slf4j
public class SentinelController {
// 1. 使用注解方式
@GetMapping("/test")
@SentinelResource(value = "test-resource",
blockHandler = "handleBlock",
fallback = "handleFallback")
public String test() {
// 模拟业务逻辑
if (Math.random() > 0.5) {
throw new RuntimeException("业务异常");
}
return "Success";
}
// 限流处理
public String handleBlock(BlockException ex) {
log.warn("请求被限流: {}", ex.getMessage());
return "请求过于频繁,请稍后重试";
}
// 熔断降级处理
public String handleFallback(Throwable t) {
log.error("业务异常: {}", t.getMessage());
return "服务暂不可用,请稍后重试";
}
// 2. 编程式方式
@GetMapping("/programmatic")
public String programmatic() {
try (Entry entry = SphU.entry("programmatic-resource")) {
// 业务逻辑
return "编程式限流控制成功";
} catch (BlockException ex) {
return "请求被限流";
}
}
// 3. 热点参数限流
@GetMapping("/hot/{id}")
@SentinelResource(value = "hot-resource",
blockHandler = "handleHotBlock")
public String hotParam(@PathVariable String id) {
return "热点参数: " + id;
}
public String handleHotBlock(String id, BlockException ex) {
return "热点参数 " + id + " 触发限流";
}
}
自定义资源配置
@Component
@PostConstruct
public class SentinelRuleConfig {
@PostConstruct
public void initRules() {
// 1. 流控规则
List<FlowRule> flowRules = new ArrayList<>();
FlowRule flowRule = new FlowRule();
flowRule.setResource("test-resource");
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS); // QPS模式
flowRule.setCount(10); // 阈值为10
flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP); // 预热模式
flowRule.setWarmUpPeriodSec(10); // 预热时间10秒
flowRules.add(flowRule);
FlowRuleManager.loadRules(flowRules);
// 2. 降级规则
List<DegradeRule> degradeRules = new ArrayList<>();
DegradeRule degradeRule = new DegradeRule();
degradeRule.setResource("test-resource");
degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT); // 响应时间模式
degradeRule.setCount(100); // 平均响应时间超过100ms
degradeRule.setTimeWindow(10); // 熔断时间10秒
degradeRules.add(degradeRule);
DegradeRuleManager.loadRules(degradeRules);
// 3. 系统规则
List<SystemRule> systemRules = new ArrayList<>();
SystemRule systemRule = new SystemRule();
systemRule.setHighestSystemLoad(10.0); // 最大系统负载
systemRule.setAvgRt(100); // 平均响应时间
systemRule.setMaxThread(1000); // 最大线程数
systemRules.add(systemRule);
SystemRuleManager.loadRules(systemRules);
// 4. 热点参数规则
List<ParamFlowRule> paramFlowRules = new ArrayList<>();
ParamFlowRule paramFlowRule = new ParamFlowRule("hot-resource");
paramFlowRule.setCount(5); // 每秒最多5次
paramFlowRule.setDurationInSec(1);
// 设置特定参数值例外
ParamFlowItem item = new ParamFlowItem();
item.setClassType(String.class.getName());
item.setCount(100); // 特定参数值阈值更高
item.setObject("special");
paramFlowRule.setParamFlowItemList(Collections.singletonList(item));
paramFlowRules.add(paramFlowRule);
ParamFlowRuleManager.loadRules(paramFlowRules);
}
}
Spring Cloud 整合 Sentinel
依赖配置
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2021.0.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Feign整合
// Feign客户端
@FeignClient(name = "service-provider", fallback = ProductServiceFallback.class)
public interface ProductService {
@PostMapping("/product/update")
@SentinelResource(value = "update-product",
blockHandler = "handleBlock",
fallback = "handleFallback")
Result updateProduct(@RequestBody Product product);
}
// 熔断降级实现
@Component
public class ProductServiceFallback implements ProductService {
@Override
public Result updateProduct(Product product) {
return Result.error("服务熔断,暂时无法更新商品");
}
}
// Feign配置
@Configuration
public class FeignConfiguration {
@Bean
public RequestInterceptor requestInterceptor() {
return template -> {
// 传递用户信息
template.header("userId", "123456");
};
}
}
RestTemplate整合
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
@SentinelRestTemplate(
blockHandlerClass = SentinelHandler.class,
blockHandler = "handleException",
fallbackClass = SentinelHandler.class,
fallback = "handleError"
)
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
// 处理器类
public class SentinelHandler {
// 限流处理
public static String handleException(String url, BlockException ex) {
return "服务限流: " + ex.getMessage();
}
// 熔断降级
public static String handleError(String url, Throwable t) {
return "服务降级: " + t.getMessage();
}
}
网关整合 Sentinel
Gateway整合
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
<version>2021.0.5.0</version>
</dependency>
@Configuration
public class GatewayConfig {
@PostConstruct
public void initGatewayRules() {
// API分组限流
Set<ApiDefinition> apiDefinitions = new HashSet<>();
ApiDefinition api = new ApiDefinition("product-api")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem()
.setPattern("/product/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
apiDefinitions.add(api);
GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitions);
// 网关流控规则
Set<GatewayFlowRule> rules = new HashSet<>();
GatewayFlowRule rule = new GatewayFlowRule("product-api")
.setCount(100)
.setIntervalSec(1);
rules.add(rule);
GatewayRuleManager.loadRules(rules);
}
}
整合 Sentinel 控制台
启动 Sentinel 控制台
# 下载控制台JAR wget https://github.com/alibaba/Sentinel/releases/download/1.8.6/sentinel-dashboard-1.8.6.jar # 启动控制台 java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -jar sentinel-dashboard-1.8.6.jar
配置推送 Nacos(生产环境)
spring:
cloud:
sentinel:
datasource:
ds1:
nacos:
server-addr: localhost:8848
data-id: ${spring.application.name}-sentinel-rules
group-id: DEFAULT_GROUP
data-type: json
rule-type: flow # 规则类型
// Nacos监听器,实现动态规则推送
@Component
public class NacosConfigListener {
@PostConstruct
public void init() throws Exception {
// 监听Nacos配置变化
String dataId = "sentinel-rules";
String group = "DEFAULT_GROUP";
ConfigService configService = NacosFactory.createConfigService("localhost:8848");
configService.addListener(dataId, group, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
// 解析配置,更新规则
List<FlowRule> rules = JSON.parseArray(configInfo, FlowRule.class);
FlowRuleManager.loadRules(rules);
}
@Override
public Executor getExecutor() {
return null;
}
});
}
}
参数设计最佳实践
public class SentinelBlockHandler {
// 统一异常处理
@ExceptionHandler(BlockException.class)
@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public Result handleBlockException(BlockException e) {
Result result = new Result();
result.setCode(429);
result.setMessage("系统繁忙,请稍后重试");
// 记录限流日志
log.warn("Sentinel限流: resource={}, rule={}",
e.getRule().getResource(), e.getRule());
return result;
}
// 自定义限流逻辑
public static Result handleBlockByParam(String param, BlockException ex) {
// 针对不同参数的降级策略
Map<String, Object> data = new HashMap<>();
data.put("param", param);
data.put("fallback", true);
return Result.error(data, "限流降级");
}
}
监控指标收集
@Component
public class SentinelMetricsCollector {
@Scheduled(fixedRate = 60000) // 每分钟收集一次
public void collectMetrics() {
// 获取所有资源的统计信息
Map<ResourceWrapper, ClusterNode> clusterNodes =
ClusterBuilderSlot.getClusterNodeMap();
for (Map.Entry<ResourceWrapper, ClusterNode> entry :
clusterNodes.entrySet()) {
ClusterNode node = entry.getValue();
Metrics metrics = new Metrics();
metrics.setResource(entry.getKey().getName());
metrics.setPassQps(node.passQps());
metrics.setBlockQps(node.blockQps());
metrics.setExceptionQps(node.exceptionQps());
metrics.setAvgRt(node.avgRt());
metrics.setCurThreadNum(node.curThreadNum());
// 发送到监控系统(Prometheus、Grafana等)
sendToMonitorSystem(metrics);
}
}
}
这个整合案例涵盖了 Sentinel 在 Spring Boot、Spring Cloud、Gateway 等主流框架中的使用,包含了规则配置、熔断降级、限流控制、控制台整合等核心功能。