import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
// 旧版是ZuulFallbackProvider
@Component
public class BaoziZuulFallbackProvider implements FallbackProvider {
// 为哪个服务提供回退
@Override
public String getRoute() {
return "zuul-provider";
}
@Override
public ClientHttpResponse fallbackResponse(String s, Throwable throwable) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
// fallback时的状态码
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
// 数字类型状态码 本例返回的其实就是200
return this.getStatusCode().value();
}
@Override
public String getStatusText() throws IOException {
// 状态文本 本例返回的就是OK
return this.getStatusCode().getReasonPhrase();
}
@Override
public void close() {}
@Override
public InputStream getBody() throws IOException {
// 响应体
return new ByteArrayInputStream("服务不可用,稍后再试".getBytes());
}
@Override
public HttpHeaders getHeaders() {
// 响应header
HttpHeaders headers = new HttpHeaders();
MediaType mt = new MediaType("application","json", Charset.forName("UTF-8"));
headers.setContentType(mt);
return headers;
}
};
}
}
网友评论