springcloud 熔断处理

在springcloud微服务中,有时候一个服务挂了,我们需要友好的提示,此时我们在api网关路由上做一下过滤,进行友好的提示处理.

代码如下:

  

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lujiangchuangzhu.seventeen.api.gateway.vo.BaseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

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

/**
 *Zull路由发起请求失败时的回滚处理
 * Created by hmb on 2018/3/29.
 */
@Slf4j
@Component
public class GenericFallbackProvider implements FallbackProvider {


    @Override
    public ClientHttpResponse fallbackResponse(Throwable throwable) {
        log.info("服务调用出现了异常:"+throwable.getMessage());
        throwable.printStackTrace();
        return callback();
    }

    /**
     * 如果需要所有调用都支持回退,则return "*"或return null
     * @return
     */
    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return callback();
    }

    private  ClientHttpResponse callback(){
        return new ClientHttpResponse(){

            @Override
            public InputStream getBody() throws IOException {
                ObjectMapper mapper = new ObjectMapper();
                BaseVO vo=new BaseVO();
                vo.setCode(10000);
                vo.setMessage("服务器开小差了,请稍后再试!");
                String json = mapper.writeValueAsString(vo);
                return new ByteArrayInputStream(json.getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                //和body中的内容编码一致,否则容易乱码
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }

            /**
             * 网关向api服务请求是失败了,但是消费者客户端向网关发起的请求是OK的,
             * 不应该把api的404,500等问题抛给客户端
             * 网关和api服务集群对于客户端来说是黑盒子
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {


            }

        };
    }
}
FallbackProvider 对这个接口实现就可以了.
posted @ 2018-04-17 14:16  全力以赴001  阅读(1922)  评论(0编辑  收藏  举报