如果需要,您可以实现自己的FallbackProvider并根据原因自定义响应。
比如:
@Component
public class CustomFallbackBasedOnCause implements FallbackProvider {
private static final String DEFAULT_MSG = "{\"success\": false,\"message\": \"Service is down. Please try later\"}";
@Override
public String getRoute() {
return "*"; // * = all routes
}
@Override
public ClientHttpResponse fallbackResponse(final Throwable cause) {
if (cause instanceof HystrixTimeoutException) {
return response(HttpStatus.GATEWAY_TIMEOUT);
} else {
return fallbackResponse();
}
}
@Override
public ClientHttpResponse fallbackResponse() {
return response(HttpStatus.INTERNAL_SERVER_ERROR);
}
private ClientHttpResponse response(final HttpStatus status) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return status;
}
@Override
public int getRawStatusCode() throws IOException {
return status.value();
}
@Override
public String getStatusText() throws IOException {
return status.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream(DEFAULT_MSG.getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
}
正如你在
getRoute()
方法,可以指定此CustomFallback是否将用于所有路由(
return "*"
)或特定路线。
如果您使用注册表服务(例如Eureka)。您不必指定路由URL,而是指定服务ID。
return "SERVICEID"