天天看點

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初識篇—容錯機制