Zuul之路由熔断

Zuul作为Netflix组件,可以与Ribbon、Eureka、Hystrix等组件结合,实现负载均衡、熔断器的功能

Spring boot2X集成zuul与consul实现负载均衡和反向代理

当后端服务出现异常时,不希望将异常抛出给最外层,期望服务可以自动进行一降级,返回预设的信息

熔断器的功能需要实现FallbackProvider接口

package com.louis.mango.zuul;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

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;

@Component
public class MyFallbackProvider implements FallbackProvider {
    @Override
    public String getRoute() {
        return "consumer";
    }

    @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 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "ok";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("Sorry,the service consumer is not available now.".getBytes()); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return headers; } }; } }

重新启动服务,provider服务可以正常访问,交替返回

hello,provider 或 hello,another provider

当停掉provide服务时,会返回

Sorry,the service consumer is not available now.

说明:

  MyFallbackProvider实现了两个方法

    getRoute() 指定熔断器功能应用于哪些路由的服务

    fallbackResponse() 进入熔断器执行的逻辑

 

posted @ 2019-12-01 00:10  慕尘  阅读(639)  评论(0编辑  收藏  举报