springcloud学习第四篇

一、快速使用

1.添加依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

2.添加配置

hystrix:
  command:
    default: # 全局默认配置
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000 # 设置命令执行超时时间为3秒
      circuitBreaker:
        requestVolumeThreshold: 20 # 10秒内请求数达到20次时才可能触发熔断
        errorThresholdPercentage: 50 # 错误百分比达到50%时触发熔断
        sleepWindowInMilliseconds: 5000 # 熔断开启后,5秒后尝试恢复
      fallback:
        enabled: true # 启用降级
# 开启feign支持hystrix 默认是关闭的
feign: 
	hystrix:
		enabled: true

3.启用 Hystrix

@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients(basePackages = "com.jhk")
@EnableHystrix
public class AppUserApplication {
    public static void main(String[] args) {
        SpringApplication.run(AppUserApplication.class, args);
    }
}

4.编写服务与降级逻辑

@Service
public class MyService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public String callRemoteService() {
        // 调用远程服务
        return restTemplate.getForObject("http://example-service/data", String.class);
    }

    // 降级方法,方法签名需与原方法一致,且必须在同一个类中
    public String fallbackMethod() {
        // 返回一个友好的错误提示
        return "Service is unavailable, please try again later.";
    }
}

5.结合Feign

@FeignClient(name = "service-name", fallbackFactory = ServiceFallbackFactory.class)
public interface ServiceClient {
    @GetMapping("/api/data")
    String getData();
}


@Component
public class ServiceFallbackFactory implements FallbackFactory<ServiceClient> {

    private static final Logger log = LoggerFactory.getLogger(ServiceFallbackFactory.class);

    @Override
    public ServiceClient create(Throwable cause) {
        // 在这里可以访问到具体的异常信息 cause
        return () -> {
            log.error("调用 service-name 失败,原因:", cause);
            return "Fallback response due to: " + cause.getMessage();
        };
    }
}

二、Hystrix默认配置跳闸阈值

1.宕机跳闸

注册中心没有服务提供者实例

hystrix:
  command:
    default: # 全局默认配置
      circuitBreaker:
        requestVolumeThreshold: 20 # 10秒内请求数达到20次时才可能触发熔断

2.超时跳闸

注册中心服务提供者实例响应时间过长

hystrix:
  command:
    default: # 全局默认配置
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000 # 设置命令执行超时时间为3秒

3.异常跳闸

注册中心服务提供者实例响应异常

hystrix:
  command:
    default: # 全局默认配置
      circuitBreaker:
      	errorThresholdPercentage: 50 # 错误百分比达到50%时触发熔断

三、断路器三种状态转换

Snipaste_2026-06-17_17-24-48

1.关闭

当请求成功时,断路器处于关闭状态。

当请求失败比例低于阈值时,断路器处于关闭状态。在时间滑动窗口内(timeInMilliseconds)内,请求失败次数/请求总数 小于 errorThresholdPercentage 错误百分比(默认50%)

2.开启

当请求失败比例高于于阈值时,断路器处于关闭状态。在时间滑动窗口内(timeInMilliseconds)内,请求失败次数/请求总数 大于 errorThresholdPercentage 错误百分比(默认50%)

3.半开

时间窗口结束(sleepWindowInMilliseconds),处于半开状态。半开状态允许一次请求,请求成功则断路器转为关闭,失败则断路器转为打开然后再次循环。

四、Hystrix服务调用的内部逻辑

hystrix:
  threadpool:
    # 此处使用的key,必须与 @HystrixCommand 中 threadPoolKey 的值完全一致
    userServiceThreadPool:
      # 核心线程数,默认10
      coreSize: 20
      # 最大线程数,需配合 allowMaximumSizeToDivergeFromCoreSize: true 使用
      maximumSize: 30
      allowMaximumSizeToDivergeFromCoreSize: true
      # 队列最大容量,-1表示使用SynchronousQueue
      maxQueueSize: 50
      # 队列拒绝阈值,动态控制队列拒绝
      queueSizeRejectionThreshold: 10
@Service
public class MyService {

    // 为这个方法定义一个独立的线程池,标识为 "userServiceThreadPool"
    @HystrixCommand(
        fallbackMethod = "fallbackMethod",
        threadPoolKey = "userServiceThreadPool" // 指定线程池的唯一标识
    )
    public String callRemoteService() {
        // ... 调用远程服务的逻辑
        return "success";
    }

    public String fallbackMethod() {
        return "fallback";
    }
}

Snipaste_2026-06-19_16-12-33

1.构建Hystrix的Command 对象,调用执行方法

2.Hystrix检查当前服务的熔断器开关是否开启,若开启,则执行降级服务fallbackMethod方法

3.若熔断器开关关闭,则Hystrix检查当前服务的线程池是否能接收新的请求,若线程池已满则执行降级服务fallbackMethod方法

4.若线程池接受请求,则Hystrix开始执行服务调用具体逻辑run方法

5.若服务执行失败,则执行降级服务fallbackMethod方法,并将执行结果上报Metrics更新服务健康状况

6.若服务执行超时,则执行降级服务fallbackMethod方法,并将执行结果上报Metrics更新服务健康状况

7.若服务执行成功,返回正常结果

8.若服务降级fallbackMethod方法执行成功,则返回降级结果

9.若服务降级fallbackMethod方法执行失败,则抛出异常

本文来自博客园,作者:TheLifelongLearner,转载请注明原文链接:https://www.cnblogs.com/The-Lifelong-Learner/p/20608010

posted @ 2026-06-17 17:37  TheLifelongLearner  阅读(14)  评论(0)    收藏  举报