天天看点

springcloud之Zuul初识篇—容错机制

上一篇描述了过滤器异常时执行error类型过滤器处理,当网关转发请求给业务模块出现异常时通过容错机制来处理。

代码:

import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixTimeoutException;
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;


@Component
public class Test1FallBack implements FallbackProvider {
    @Override
    public String getRoute() {
        //写null或“*”则所有服务的调用错误都会由这个方法处理
        //写服务名则该方法只处理调用该服务而出现的异常
        return "test1";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        System.out.println("route:"+route);
        ClientHttpResponse httpResponse;
        if(cause instanceof HystrixBadRequestException){
            httpResponse = response(HttpStatus.BAD_REQUEST);
        }else if(cause instanceof HystrixTimeoutException) {
            httpResponse = response(HttpStatus.REQUEST_TIMEOUT);
        }else{
            httpResponse = response(HttpStatus.UNAUTHORIZED);
        }
        return httpResponse;
    }

    private ClientHttpResponse response(HttpStatus status){
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return status;
            }

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

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

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String msg = "{\"msg\":\"test1指定回调\"}";
                return new ByteArrayInputStream(msg.getBytes());
            }

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

    }
}
           

测试:关闭服务提供者---test1,正常请求

服务连接超时,出现异常,进入该容错方法。

springcloud之Zuul初识篇—容错机制