GoodsServiceFallBackProvider.java 2.3 KB
Newer Older
Q
qinyingjie 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
package com.kwan.springcloud;


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;

/**
 * FallbackProvider(请求异常处理)
 * <p>
 * 网关的默认回退FallbackProvider的机制只适用于通过配置文件中配置的url来跨服务调用,而不拦截通过FeignClient跨服务调用,
 * 也就是说要自己实现一个FeignClient服务的fallback才可以,但是如果通过FeignClient的服务要是特别多怎么办,每一个都要写一个不得累死,
 * 这里想到了通过网关的错误过滤器来统一处理FeignClient跨服务调用出错的问题
 *
 * @author : qinyingjie
 * @version : 2.2.0
 * @date : 2023/1/11 12:48
 */
@Component
public class GoodsServiceFallBackProvider implements FallbackProvider {

    @Override
    public String getRoute() {
        return "goods-service";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("order-service is not available!".getBytes());
            }

            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.BAD_REQUEST;
            }

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

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

            @Override
            public void close() {

            }
        };
    }

}