Hystrix配置步骤
- 引入依赖:在库存服务的
pom.xml
文件中添加Hystrix依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 启用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);
}
}
- 配置Hystrix属性:在
application.yml
文件中配置Hystrix相关属性。
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000 # 命令执行超时时间,单位毫秒
circuitBreaker:
requestVolumeThreshold: 10 # 在滚动时间窗内,请求次数达到此值,熔断器才会开启检查
sleepWindowInMilliseconds: 5000 # 熔断器开启后,休眠时间窗,单位毫秒
errorThresholdPercentage: 50 # 错误率达到此值,熔断器开启
熔断策略设置
- 请求次数阈值:
requestVolumeThreshold
定义在滚动时间窗内,至少要有多少请求,熔断器才会开启检查。例如设置为10,表示10次请求内即使有失败,熔断器也不会开启。
- 错误率阈值:
errorThresholdPercentage
表示在请求次数达到requestVolumeThreshold
后,如果错误率达到此值(如50%),熔断器就会开启。
- 休眠时间窗:
sleepWindowInMilliseconds
指定熔断器开启后,经过此时间窗,熔断器会进入半开状态,尝试放行部分请求。
回退方法设计
- 方法定义:在需要熔断保护的方法所在类中,定义一个回退方法。回退方法的签名必须与原方法一致,且添加
@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;
}
}
- 回退逻辑:回退方法中应包含在原方法失败时的替代逻辑,如返回友好的提示信息,避免给用户抛出异常,保证系统的稳定性和用户体验。