Code
/**
* @author luobo.cs@raycloud.com
* @since 2020/8/2 3:49 下午
*/
public class TimeOutCommand extends HystrixCommand<Boolean> {
final Logger log = LoggerFactory.getLogger(this.getClass());
private final DbConfig dbConfig;
public TimeOutCommand(DbConfig dbConfig) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("fast-timeout"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(dbConfig.getName()))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(10000).withExecutionTimeoutEnabled(true))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withMaxQueueSize(300).withCoreSize(10)));
this.dbConfig = dbConfig;
}
@Override
protected Boolean run() {
try {
DBUtils.testConn(dbConfig);
return Boolean.TRUE;
} catch (Exception e) {
log.error("[TimeOutCommand][error:{}]", e.getMessage(), e);
return Boolean.FALSE;
}
}
@Override
protected Boolean getFallback() {
log.error("出现降级 GG:{}", JSONObject.toJSONString(dbConfig));
return Boolean.FALSE;
}
}
使用
TimeOutCommand timeOutCommand = new TimeOutCommand(config);
//这里的使用根据实际情况使用,例如有的场景需要同步,有的场景需要异步
//同步execute 异步 observe
final Boolean execute = timeOutCommand.execute();
//异步
Observable<Response<String>> observe = timeOutCommand.observe();
observe.subscribe(new Observer<Response<String>>() {
@Override
public void onCompleted() {
//没有什么东西
}
@Override
public void onError(Throwable e) {
//这里可无视
}
@Override
public void onNext(Response<String> response) {
//降级或者不降级都会走这里
if (response.getSuccess()) {
try {
TOMCAT_STATUS.put(tomcat.getTomcatId(), response.getBody().split("\\t")[2]);
} catch (Exception e) {
TOMCAT_STATUS.put(tomcat.getTomcatId(), e.getMessage());
}
} else {
TOMCAT_STATUS.put(tomcat.getTomcatId(), response.getErrorMsg());
}
}
});
——————————
2021-01-06
对于豪猪的不了解,导致设置的有问题
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(dbConfig.getName()))
这里会为每一个 dbConfig.getName
都生成一个线程池,所以随着name的增加,线程开始💥 爆炸。 这里需要明确是否要隔离. 例如我只想要的功能只要一个线程池就够了