目录
断路器(Hystrix)
1. 基本概念
2. 工作原理
3. 主要功能
场景示例
1. 项目准备
2. 添加依赖
3. 启用 Hystrix
4. 定义服务调用方法并添加 Hystrix 注解
5. 在控制器中调用服务方法
6. 测试
在微服务架构中,服务之间通常存在大量的依赖关系。当某个下游服务出现故障或响应超时,可能会导致调用它的上游服务出现请求堆积、资源耗尽,最终引发整个系统的雪崩效应。断路器(Circuit Breaker)就是为了解决这个问题而出现的一种设计模式。
Hystrix 是 Netflix 开源的一个用于实现断路器模式的库,Spring Cloud 对其进行了集成,提供了简单易用的方式来使用 Hystrix 的功能。Hystrix 可以监控服务调用的状态,当某个服务的调用失败率超过一定阈值时,会自动 “跳闸”,即开启断路器,后续的请求将不再调用该服务,而是直接执行预设的降级逻辑,从而避免故障的扩散,保证系统的稳定性。
假设有两个微服务:order-service
(订单服务)和 product-service
(商品服务),order-service
需要调用 product-service
的接口获取商品信息。
在 order-service
的 pom.xml
中添加 Hystrix 相关依赖:
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
在 order-service
的主类上添加 @EnableCircuitBreaker
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableCircuitBreaker;
@SpringBootApplication
@EnableCircuitBreaker
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ProductService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "getProductFallback")
public String getProductInfo() {
String url = "http://product-service/products";
return restTemplate.getForObject(url, String.class);
}
public String getProductFallback() {
return "Product service is unavailable. Please try again later.";
}
}
解释:
@HystrixCommand
注解用于标记需要进行熔断处理的方法。fallbackMethod
属性指定了降级方法,当 getProductInfo
方法调用失败时,会自动调用 getProductFallback
方法。import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
@Autowired
private ProductService productService;
@GetMapping("/orders/products")
public String getOrderProducts() {
return productService.getProductInfo();
}
}
product-service
和 order-service
。order-service
的 /orders/products
接口,会调用 product-service
的接口获取商品信息。product-service
故障(如停止 product-service
服务),再次访问 /orders/products
接口,此时 Hystrix 会触发熔断机制,执行降级方法,返回 Product service is unavailable. Please try again later.
。通过以上步骤,你可以看到如何使用 Hystrix 实现服务的熔断和降级处理,提高系统的容错能力。需要注意的是,Spring Cloud 已经逐渐将重心转移到 Resilience4j 等替代方案上,但 Hystrix 仍然是一个广泛使用的断路器实现。