package com.sdyy.zuul.config;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.springframework.http.client.ClientHttpResponse;
import java.io.InputStream;
import org.springframework.http.HttpHeaders;
/**
* @author lizz
* @title: ZuulFallback
* @projectName monitor_server
* @description: TODO
* @date 2019/9/2413:05
*/
@Component
public class ZuulFallback implements FallbackProvider {
@Override
public String getRoute() {
return "*";//api服务id,如果需要所有调用都支持回退,则return "*"或return null
}
public ClientHttpResponse fallbackResponse() {
return null;
}
@Override
public ClientHttpResponse fallbackResponse(String route, final Throwable cause) {
if (cause instanceof HystrixTimeoutException) {
return response(HttpStatus.GATEWAY_TIMEOUT);
} else {
return response(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private ClientHttpResponse response(final HttpStatus status) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
//return status;
return HttpStatus.BAD_REQUEST;
}
@Override
public int getRawStatusCode() throws IOException {
//return status.value();
return HttpStatus.BAD_REQUEST.value();
}
@Override
public String getStatusText() throws IOException {
//return status.getReasonPhrase();
//return HttpStatus.BAD_REQUEST.name();
return HttpStatus.BAD_REQUEST.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream(("fallback:"+ZuulFallback.this.getRoute()).getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
}
参考:https://blog.csdn.net/MobiusStrip/article/details/84099725
https://blog.csdn.net/qq_24504315/article/details/79121938