我们通过直接扩展HystrixCommand类来使用Hystrix功能。但是对于一些业务异常,会触发Hystrix的回退方法。
我不想针对某些业务特定异常触发Hystrix回退。我该如何在不使用注释的情况下实现?
@HystrixCommand(ignoreExceptions = { BaseException.class, MissingServletRequestParameterException.class, TypeMismatchException.class })
@Override
protected Object run() throws Exception {
try {
return //call goes here
}
catch (Throwable e) {
//We wrap any exceptions in a HystrixBadRequestException because this way any other errors will not
//trip the short circuit
throw new HystrixBadRequestException("Exception thrown hystrix call", e);
}
}
有两种方法来实现这个。
Using HystrixCommand annotation and specifying the exception types.
@HystrixCommand(ignoreExceptions = { HttpStatusCodeException.class, JsonMappingException.class })
Using "HystrixBadRequestException" and customize your code in way to just ignore few exception cases or status codes. This implementation will check for specific error codes on exceptions expected with you backend API contract and does not invoke hystrix fallback. Throwing "HystrixBadRequestException" will not count as hystrix fault.
@HystrixCommand(commandKey = "MyHystrixCommand", fallbackMethod = "myHystrixFallback", threadPoolKey = "ThreadPoolKey")
public ResponseEntity<String> getServiceCallResponse(String serviceUrl, HttpEntity<?> entity) {
ResponseEntity<String> resp = null;
try {
resp = restTemplate.exchange(serviceUrl, HttpMethod.POST, entity, String.class)
.getBody();
}
catch(Exception e) {
handleExceptionForHystrix("getServiceCallResponse", e);
}
return resp;
}
private void handleExceptionForHystrix(String function, Exception e) {
if (e instanceof HttpStatusCodeException) {
HttpStatus httpStatusCode = ((HttpStatusCodeException)e).getStatusCode();
if(httpStatusCode.equals(HttpStatus.BAD_REQUEST) || httpStatusCode.equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
throw new HystrixBadRequestException("Hystrix Bad Request Exception Occurred" + httpStatusCode, e);
}
throw new RuntimeException(function, e);
}
throw new RuntimeException(function, e);
}
public ResponseEntity<String> myHystrixFallback(String serviceUrl, HttpEntity<?> entity, Throwable hystrixCommandExp) {
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
HystrixCommand
中没有这样的属性。 - Simon Forsberg