微服务保护概述

微服务架构中,服务间依赖复杂,需通过限流、熔断、降级等手段保障系统稳定性。《黑马商城》采用Spring Cloud Alibaba组件实现微服务保护,核心包括Sentinel流量控制、熔断降级、系统自适应保护等机制。

Sentinel基础集成

pom.xml中添加依赖:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

application.yml中配置控制台地址:

spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080 # Sentinel控制台地址

流量控制规则

通过@SentinelResource定义资源并配置限流规则:

@GetMapping("/order/{id}")
@SentinelResource(value = "getOrder", blockHandler = "blockHandlerMethod")
public Order getOrder(@PathVariable Long id) {
    return orderService.findById(id);
}

// 限流处理逻辑
public Order blockHandlerMethod(Long id, BlockException ex) {
    return Order.error("请求过于频繁,请稍后重试");
}

在Sentinel控制台中配置QPS阈值为100,超出后触发限流逻辑。

熔断降级策略

基于异常比例触发熔断:

@SentinelResource(
    value = "createOrder", 
    fallback = "fallbackMethod",
    exceptionsToIgnore = {IllegalArgumentException.class}
)
public Order createOrder(OrderDTO dto) {
    // 业务逻辑
}

// 降级处理
public Order fallbackMethod(OrderDTO dto, Throwable t) {
    return Order.error("服务暂时不可用");
}

配置规则:当异常比例超过50%(统计时长5秒),自动熔断10秒。

系统自适应保护

Sentinel根据系统负载(如CPU使用率、平均RT)动态调整流量:

spring:
  cloud:
    sentinel:
      filter:
        enabled: false # 关闭所有HTTP请求的默认限流
      flow:
        cold-factor: 3 # 冷启动因子

规则持久化方案

采用Nacos存储规则配置,避免重启失效:

@Bean
public DataSource nacosDataSource() {
    return new NacosDataSource(
        "nacos-server:8848", "sentinel-rules",
        "DEFAULT_GROUP", new Converter<String, List<FlowRule>>() {
            // 规则解析逻辑
        }
    );
}

监控与告警

集成Prometheus采集指标:

management:
  endpoints:
    web:
      exposure:
        include: prometheus

配置Grafana仪表盘实时展示QPS、拒绝请求数等关键指标。


通过以上措施,《黑马商城》实现了多层次保护:流量控制防止突发请求击垮系统,熔断降级快速隔离故障服务,系统自适应保护应对不可预测流量峰值。实际部署时需根据压测结果调整阈值参数。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐