11Zuul FallBack · SpringCloud微服务实战 · 看云

11.Zuul FallBack

导航

本节代码地址


虽然上一节我们配置了重试机制,但是重试次数结束了没成功任然会失败,比如如下错误,因为Spring Cloud Zuul 里面已经集成了Hystrix,我们可以自己定义回退机制。

Caused by: java.net.SocketTimeoutException: Read timed out

11.1 新建FallBack 类

实现回退需要实现FallbackProvider接口


@Slf4j
@Component
public class ZuulFallBack implements FallbackProvider {
    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                RequestContext ctx=RequestContext.getCurrentContext();
                Throwable throwable = ctx.getThrowable();
                if(null!=throwable){
                    log.error("Zuul发生错误,{}",throwable.getCause().getMessage());
                    FwResult<String> byteMsg = FwResult.failed(throwable.getCause().getMessage(), "网络或服务异常");
                    return new ByteArrayInputStream(JSONUtil.toJsonStr(byteMsg).getBytes());
                }
                FwResult<String> byteMsg = FwResult.failedMsg("网络或服务异常");
                return new ByteArrayInputStream(JSONUtil.toJsonStr(byteMsg).getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers=new HttpHeaders();
                MediaType mediaType=new MediaType("application", "json", StandardCharsets.UTF_8);
                headers.setContentType(mediaType);
                return headers;
            }
        };
    }
}

  • getRoute 方法中返回*表示对所有服务进行回退操作,如果只想对某个服务进行回退,
    那么就返回需要回退的服务名称,这个名称是注册到Eureka中的名称
  • ClientHttpResponse 构造回退的内容
  • getStatusCode 返回响应的状态码
  • getStatusText 返回响应状态码对应的文本
  • getBody 返回回退的内容
  • getHeaders 返回响应的请求头信息

11.2 设置hystrix 超时时间

假设设置1秒

#回退超时时间
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000

11.3 重启服务

浏览器或Postman 输入地址localhost:8679/ribbon/user/1,如果想快速看到,可以将fw-cloud-ribbon-server关掉

9a96e3140f68c95498175f38ab9789eb_MD5.png