public class GetStockServiceCommand extends HystrixCommand<String>{
private StockService stockService;
public GetStockServiceCommand(StockService stockService){
super(setter());
this.stockService = stockService;
}
private static Setter setter(){
//服务分组
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("stock");
...
//命令配置
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
...
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
.withFallbackEnabled(true)//默认为true
.withFallbackIsolationSemaphoreMaxConnectionRequest(100)
.withExecutionIsolationThreadInterrupOnFutureCCancel(true)
.withExecutionIsolationThreadInterrupOnTimeout(true)
.withExecutionTimeoutEnabled(true)
.withExecutionTimeoutInMilliseconds(1000);
return HystrixCommand.Setter.withGroupKey(groupKey)
.addCCommandPropertiesDefaults(commandProperties)
}
@Override
protected String run() throws Exception{
//可以通过抛出异常,或Thread.sleep模拟超时
return stockService.getStock();
}
@Override
protected String getFallback(){
return "有货";
}
}
使用Hystrix实现服务降级
最新推荐文章于 2024-05-13 14:09:30 发布