Sentinel 集成

返回 Spring Cloud

Sentinel 是 Spring Cloud Alibaba 推荐的流量治理组件(限流、熔断、系统保护),与 Resilience4j 可并存:Sentinel 偏规则中心与控制台,Resilience4j 偏代码注解(见 熔断与限流)。原理见 Sentinel


依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 网关限流 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

配置

spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719
      eager: true
    nacos:
      # 规则持久化到 Nacos(可选)
      server-addr: 127.0.0.1:8848

资源定义

@SentinelResource

@SentinelResource(
    value = "getOrder",
    blockHandler = "getOrderBlock",
    fallback = "getOrderFallback"
)
public Order getOrder(Long id) {
    return orderClient.fetch(id);
}
 
public Order getOrderBlock(Long id, BlockException ex) {
    throw new BizException("限流中,请稍后");
}
 
public Order getOrderFallback(Long id, Throwable t) {
    return Order.empty();
}

OpenFeign 集成

feign:
  sentinel:
    enabled: true

Feign 接口自动成为 Sentinel 资源,可在 Dashboard 配置流控规则。


Gateway 限流

spring:
  cloud:
    gateway:
      routes:
        - id: order
          uri: lb://order-service
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20
            - name: SentinelGatewayFilter

或使用 Sentinel Gateway 流控规则(API 分组、热点参数)。

网关 Redis 限流:API 网关Redis


规则类型

类型说明
流控QPS、线程数、关联流、链路
熔断慢调用、异常比例、异常数
热点参数秒杀 SKU、用户 ID
系统规则CPU、Load、RT 自适应

架构视角:削峰与限流高并发


Sentinel vs Resilience4j

维度SentinelResilience4j
控制台Dashboard 实时规则无官方 UI
生态Alibaba、GatewaySpring Cloud 官方常用
文档SentinelResilience4j

相关链接