持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情
1、前言
在上一篇的分享中,我为大家介绍了如何基于Hystrix的timeout机制处理三方接口调用超时问题。本次为大家详细介绍下Hystrix中详细的参数配置,以及非注解形式HystrixCommand的使用示例。
2、Hystrix参数详细介绍
Hystrix中的配置主要分为三类:1)Execution:这些主要决定Hystrix怎么去执行,比如说隔离策略,超时时间等;2、Fallback:回退相关;3、Circuit Breaker:熔断器配置;
execution:
isolation:
#指定隔离策略,默认thread线程池模式,还有信号量semaphore模式,根据信号量计数
strategy: thread/semaphore
thread:
#设置请求的超时时间,单位毫秒,默认为1000ms
timeoutInMilliseconds: 1000
#控制服务超时后是否进行中断,默认为true。(PS:如果 Hystrix 方法里没有处理中断信号的逻辑,那么中断会被忽略。)
interruptOnTimeout: true
#控制服务取消后是否进行中断,默认为false
interruptOnCancel: false
semaphore:
#信号量最大请求数,隔离策略为semaphore模式时设置,默认为10
maxConcurrentRequests: 10
#控制熔断器是否启用超时,默认为true
timeout:
enabled: true
fallback:
isolation:
semaphore:
#fallback方法最大并发量,默认为10。(PS:如果并发数达到该设置值,请求会被拒绝并抛出 REJECTED_SEMAPHORE_FALLBACK 异常并且fallback不会被调用)
maxConcurrentRequests: 10
#是否启用fallback方法回退,默认为true
enabled: true
#是否开启熔断器,默认为true
circuitBreaker:
enabled: true
#一个滑动窗口内最小的请求数。默认20,即当一个滑动窗口的时间内(比如说10秒)收到19个请求,即使19个请求都失败,也不会触发熔断。
requestVolumeThreshold: 20
#触发断路的时间值,默认5000ms,即触发断路器后的5000ms内的请求都会被拒绝,5000ms后才会尝试关闭断路器。
sleepWindowInMilliseconds: 5000
#请求错误比例阀值,默认50,也就是说如果超过50%的请求出错,那么就会打开断路器,触发fallback。
errorThresholdPercentage: 50
3、继承HystrixCommand类实现Hystrix控制
public class SfBannerCommand extends HystrixCommand<SfBannerInfo> {
private static Logger logger = LoggerFactory.getLogger(SfBannerCommand.class);
private String courseId;
private static final HystrixCommandKey KEY = HystrixCommandKey.Factory.asKey("SfBannerCommand");
public SfBannerCommand(String courseId) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("SfBannerInfoService"))
.andCommandKey(KEY)
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withCoreSize(8)
.withMaxQueueSize(10)
.withQueueSizeRejectionThreshold(8))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withCircuitBreakerEnabled(true)
.withCircuitBreakerRequestVolumeThreshold(20)
.withCircuitBreakerErrorThresholdPercentage(40)
.withCircuitBreakerSleepWindowInMilliseconds(3000)
// 设置是否打开超时,默认是true
.withExecutionTimeoutEnabled(true)
// 设置超时时间,默认1000(ms)
.withExecutionTimeoutInMilliseconds(500)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(30)));
this.courseId = courseId;
}
@Override
protected SfBannerInfo run() throws Exception {
System.out.println("调用接口查询三方广告数据,courseId=" + courseId);
String url = "http://localhost:8081/getSfAdInfo?courseId=" + courseId;
String response = HttpRequestPoolUtil.httpPostRequest(url);
System.out.println(response);
return JSONObject.parseObject(response, SfBannerInfo.class);
}
@Override
protected SfBannerInfo getFallback() {
SfBannerInfo sfBannerInfo = new SfBannerInfo();
sfBannerInfo.setTitle("降级Banner");
return sfBannerInfo;
}
}
好了、本期就先介绍到这里,有什么需要交流的,大家可以随时私信我。😊