MST

星途 面试题库

面试题:Spring Cloud微服务架构的业务场景应用之熔断机制

假设在一个基于Spring Cloud的电商微服务系统中,库存服务可能会出现高并发请求导致响应缓慢甚至不可用的情况。请描述如何利用Hystrix实现熔断机制,以保证整个系统的稳定性,包括Hystrix的配置步骤、熔断策略的设置以及回退方法的设计。
19.8万 热度难度
后端开发微服务架构

知识考点

AI 面试

面试题答案

一键面试

Hystrix配置步骤

  1. 引入依赖:在库存服务的pom.xml文件中添加Hystrix依赖。
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  1. 启用Hystrix:在Spring Boot应用主类上添加@EnableHystrix注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;

@SpringBootApplication
@EnableHystrix
public class InventoryServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(InventoryServiceApplication.class, args);
    }
}
  1. 配置Hystrix属性:在application.yml文件中配置Hystrix相关属性。
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000 # 命令执行超时时间,单位毫秒
      circuitBreaker:
        requestVolumeThreshold: 10 # 在滚动时间窗内,请求次数达到此值,熔断器才会开启检查
        sleepWindowInMilliseconds: 5000 # 熔断器开启后,休眠时间窗,单位毫秒
        errorThresholdPercentage: 50 # 错误率达到此值,熔断器开启

熔断策略设置

  1. 请求次数阈值requestVolumeThreshold定义在滚动时间窗内,至少要有多少请求,熔断器才会开启检查。例如设置为10,表示10次请求内即使有失败,熔断器也不会开启。
  2. 错误率阈值errorThresholdPercentage表示在请求次数达到requestVolumeThreshold后,如果错误率达到此值(如50%),熔断器就会开启。
  3. 休眠时间窗sleepWindowInMilliseconds指定熔断器开启后,经过此时间窗,熔断器会进入半开状态,尝试放行部分请求。

回退方法设计

  1. 方法定义:在需要熔断保护的方法所在类中,定义一个回退方法。回退方法的签名必须与原方法一致,且添加@HystrixCommand(fallbackMethod = "fallbackMethodName")注解。
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

@Service
public class InventoryService {

    @HystrixCommand(fallbackMethod = "getInventoryFallback")
    public String getInventory(String productId) {
        // 实际获取库存逻辑,可能会出现高并发问题
        return "Inventory details for product " + productId;
    }

    public String getInventoryFallback(String productId) {
        // 回退逻辑,当原方法失败时执行
        return "Sorry, inventory service is currently unavailable for product " + productId;
    }
}
  1. 回退逻辑:回退方法中应包含在原方法失败时的替代逻辑,如返回友好的提示信息,避免给用户抛出异常,保证系统的稳定性和用户体验。