容错机制-Spring Cloud Alibaba Sentinel 详解(包含服务雪崩现象、设置埋点、Sentinel控制台、流控也就是限流、熔断、在OpenFeign中使用Sentinel)

Spring Cloud Alibaba Sentinel 详解

官网

https://sca.aliyun.com/docs/2023/user-guide/sentinel/quick-start/?spm=7145af80.434205f.0.0.74716242oEhMef
在这里插入图片描述


1. Sentinel 安装与配置

(1) 依赖管理
<!-- pom.xml 添加依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 集成Feign时需添加 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel-feign</artifactId>
</dependency>
(2) 启动控制台
  1. 下载Sentinel控制台

    wget https://github.com/alibaba/Sentinel/releases/download/1.8.3/sentinel-dashboard-1.8.3.jar
    java -jar sentinel-dashboard-1.8.3.jar
    

    访问:http://localhost:8080(默认端口)。

  2. Spring Boot应用配置

# application.yml
spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080  # 控制台地址
        port: 8719                 # Sentinel客户端端口
      eager: true                  # 启动时加载规则

2. 核心配置文件与注解详解

(1) 配置文件关键项
配置项说明示例
transport.dashboardSentinel控制台地址(格式:IP:端口localhost:8080
transport.portSentinel客户端通信端口8719
eager是否在启动时加载规则(需配合Nacos等配置中心)true
(2) 核心注解 @SentinelResource
@SentinelResource(
    value = "getUser",          // 资源名称(必填)
    fallback = "handleFallback", // 通用降级方法(异常/限流/熔断)
    blockHandler = "handleBlock",// 限流/熔断专用处理方法
    exceptionsToIgnore = {IllegalArgumentException.class} // 忽略指定异常
)
public User getUser(String userId) { ... }

// 降级方法示例
private User handleFallback(String userId, Throwable e) {
    return new User("Fallback", "N/A");
}

3. 服务雪崩现象与熔断机制

(1) 雪崩现象
  • 定义:当大量请求调用故障服务时,导致连锁反应,最终所有服务不可用。
  • Sentinel解决方案:通过熔断机制隔离故障服务。
    在这里插入图片描述
(2) 设置熔断规则
// 代码配置熔断规则
DegradeRule rule = new DegradeRule("getUser");
rule.setCount(10)          // 触发熔断的异常次数
   .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) // 按异常比例熔断
   .setTimeWindow(10);     // 熔断时间窗口(秒)
List<DegradeRule> rules = new ArrayList<>();
rules.add(rule);
DegradeRuleManager.loadRules(rules);

4. 控制台界面操作

(1) 核心功能
  • 资源监控:查看QPS、异常率、线程数等指标。
  • 规则配置
    • 流控规则:设置QPS、线程数、并发量阈值。
    • 熔断降级:设置异常比例/次数触发熔断。
    • 系统保护:设置CPU使用率、平均RT阈值。
(2) 示例:在控制台配置限流规则
  1. 进入Flow Control标签页。
  2. 选择资源(如getUser)。
  3. 配置:
    • Metric Type:QPS
    • Grade:直接拒绝
    • Count:10(每秒最大请求量)

5. 流控(限流)配置示例

(1) 代码配置限流规则
FlowRule rule = new FlowRule("getUser");
rule.setGrade(RuleConstant.FLOW_GRAIN_SECOND) // 按秒统计
   .setCount(10)                             // 每秒最大请求量
   .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP); // 渐进式限流
List<FlowRule> rules = new ArrayList<>();
rules.add(rule);
FlowRuleManager.loadRules(rules);
(2) 基于注解的限流处理
@SentinelResource(value = "createUser", blockHandler = "handleBlock")
public User createUser(User user) {
    // 业务逻辑
}

private User handleBlock(BlockException e) {
    return new User("Blocked", "Too many requests");
}

6. 在OpenFeign中集成Sentinel

(1) 依赖与配置
<!-- 需添加Feign-Sentinel依赖 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel-feign</artifactId>
</dependency>
(2) 定义Feign客户端
@FeignClient(name = "user-service", 
             url = "http://user-service", 
             fallbackFactory = UserClientFallbackFactory.class)
public interface UserClient {
    @GetMapping("/users/{id}")
    User getUser(@PathVariable("id") String userId);
}

@Component
public class UserClientFallbackFactory implements FallbackFactory<UserClient> {
    @Override
    public UserClient create(Throwable cause) {
        return new UserClient() {
            @Override
            public User getUser(String userId) {
                return new User("Fallback", "N/A");
            }
        };
    }
}
(3) 控制台配置Feign资源

在控制台为资源user-service#getUser设置限流/熔断规则。


7. 完整代码示例

(1) 定义资源并配置熔断
@Service
public class UserService {
    @SentinelResource(
        value = "getUser",
        fallback = "handleFallback",
        blockHandler = "handleBlock",
        exceptionsToIgnore = {IllegalArgumentException.class}
    )
    public User getUser(String userId) {
        // 模拟远程调用
        return restTemplate.getForObject("http://user-service/" + userId, User.class);
    }

    private User handleFallback(String userId, Throwable e) {
        return new User("Fallback", "Service Unavailable");
    }

    private User handleBlock(String userId, BlockException e) {
        return new User("Blocked", "Too many requests");
    }
}
(2) 启动类配置
@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

8. 总结对比表格

功能Sentinel实现方式配置/注解
限流(流控)基于QPS/线程数/并发量,支持渐进式限流@SentinelResource + 控制台/代码配置流控规则
熔断根据异常比例或次数触发,支持半开恢复@SentinelResource + 控制台/代码配置熔断规则
系统保护基于CPU使用率、平均响应时间、负载等全局指标控制台配置系统规则
服务雪崩隔离熔断+降级机制隔离故障服务@SentinelResourcefallbackblockHandler 方法
OpenFeign集成通过spring-cloud-starter-alibaba-sentinel-feign自动拦截Feign请求定义FallbackFactory并标注@FeignClient

9. 注意事项

  1. 资源命名规范:建议使用服务名#方法名(如user-service#getUser)便于管理。
  2. 控制台权限:默认无鉴权,生产环境需配置安全策略。
  3. 规则持久化:配合Nacos等配置中心实现规则动态更新。
  4. 日志监控:通过logging.level.com.alibaba.csp=DEBUG开启详细日志。

通过以上配置和代码示例,可快速实现服务熔断、限流、雪崩防护,并在OpenFeign中集成Sentinel实现客户端容错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱的叹息

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值