天天看点

微服务springcloud—zuul的容错和回退zuul的容错与回退为zuul添加回退

zuul的容错与回退

1.启动项目microservice-discovery-eureka。

2.启动项目microservice-provider-user。

3.启动项目microservice-gateway-zuul。

4.启动项目microservice-hystrix-dashboard。

5.访问http://localhost:8040/users/1,可正常获得结果。

6.访问http://localhost:8040/actuator/hystrix.stream,可获得Hystrix的监控数据。

7.访问http://localhost:8030/hystrix,并在监控地址一栏填入http://localhost:8040/actuator/hystrix.stream

微服务springcloud—zuul的容错和回退zuul的容错与回退为zuul添加回退

8.关闭项目microservice-provider-user,再次访问http://localhost:8040/users/1,将会看到异常输出。

微服务springcloud—zuul的容错和回退zuul的容错与回退为zuul添加回退

下面来谈谈如何为zuul添加回退

为zuul添加回退

想要为Zuul添加回退,需要实现ZuulFallbackProvider接口,在实现类中,指定为哪个微服务提供回退,并提供一个ClientHttpResponse作为回退响应。

1.复制项目microservice-gateway-zuul,将ArtifactId修改为microservice-gateway-zuul-fallback。

2.编写zuul的回退类:

@Component
public class UserFallbackProvider implements FallbackProvider {
    public String getRoute(){
        //表明是为哪个微服务提供回退,"*"表示所有微服务
        return "*";
    }


    public ClientHttpResponse fallbackResponse(String route, Throwable cause){
        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() {
                //headers设定
                HttpHeaders headers = new HttpHeaders();
                MediaType mt = new MediaType("application",
                          "json", Charset.forName("UTF-8"));
                headers.setContentType(mt);
                return headers;
            }
        };
    }
}
           

spring2.0以上版本参考:https://www.2cto.com/kf/201806/754248.html

添加回退之后,重复之前的实验,当users微服务无法正常响应时,将会返回以下内容。

微服务springcloud—zuul的容错和回退zuul的容错与回退为zuul添加回退

本文大部分内容转载自周立的《Spring Cloud与Docker微服务架构实战》