这里以 Java 和 Spring Boot 为例进行说明。
服务降级
在服务层实现降级逻辑,当上游服务出现异常时,快速返回一个预设的降级响应:
@Service
public class OrderService {
@Autowired
private PaymentService paymentService;
public OrderResponse placeOrder(OrderRequest request) {
try {
// 调用支付服务进行支付处理
paymentService.doPayment(request.getOrderInfo());
// 其他订单处理逻辑
// ...
return new OrderResponse(OrderStatus.PLACED, "Order placed successfully");
} catch (Exception e) {
// 服务降级逻辑
log.error("Error occurred while placing order: {}", e.getMessage());
return new OrderResponse(OrderStatus.FAILED, "Failed to place order, please try again later");
}
}
}
熔断处理
使用 Spring Cloud Circuit Breaker 框架实现熔断机制:
@Service
public class PaymentService {
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResponse doPayment(PaymentInfo paymentInfo) {
// 实际的支付处理逻辑
return new PaymentResponse(PaymentStatus.SUCCESS, "Payment successful");
}
public PaymentResponse paymentFallback(PaymentInfo paymentInfo, Throwable t) {
// 熔断后的降级逻辑
log.error("Payment service failed: {}", t.getMessage());
return new PaymentResponse(PaymentStatus.FAILED, "Payment failed, please try again later");
}
}
在上面的例子中,我们使用 @CircuitBreaker
注解标记了 doPayment
方法,并指定了 fallbackMethod
为 paymentFallback
。当 doPayment
方法抛出异常时,会自动调用 paymentFallback
方法,返回一个预设的降级响应。
这里还需要在应用程序的配置文件中配置 Circuit Breaker 的相关参数,如熔断阈值、时间窗口、恢复时间等:
resilience4j.circuitbreaker:
instances:
paymentService:
sliding-window-size: 10
minimum-number-of-calls: 5
permissible-number-of-calls-in-half-open-state: 3
automatic-transition-from-open-to-half-open-state-enabled: true
wait-duration-in-open-state: 10s
通过以上的降级和熔断处理,我们可以在上游服务出现异常时,快速返回一个友好的响应,保护系统不被拖垮,同时也能给用户一个更好的体验。