优美的降级可以通过增加一个getFallback()实现来达到。该方法在各种类型的失败后执行。如: run()方法调用失败,超时,线程池,信号丢弃以及熔断器短路。
public class CommandHelloFailure extends HystrixCommand<String> {
private final String name;
public CommandHelloFailure(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() {
throw new RuntimeException("this command always fails");
}
@Override
protected String getFallback() {
return "Hello Failure " + name + "!";
}
}
该command将在每次执行后失败,下面的单元测试展示了返回getFallback()的值的实现而不是取得一个例外
@Test
public void testSynchronous() {
assertEquals("Hello Failure World!", new CommandHelloFailure("World").execute());
assertEquals("Hello Failure Bob!", new CommandHelloFailure("Bob").execute());
}