美文网首页
Spring Cloud Zuul 回退

Spring Cloud Zuul 回退

作者: 歌哥居士 | 来源:发表于2019-03-26 07:01 被阅读0次
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;
            }
        };
    }
}

相关文章

网友评论

      本文标题:Spring Cloud Zuul 回退

      本文链接:https://www.haomeiwen.com/subject/ndhhvqtx.html