Spring WebFlux:WebClient +错误发生后退

时间:2019-08-23 13:38:49

标签: spring webclient spring-webflux reactor spring-webclient

如果第一个服务不可用,我想在程序运行时设置一个后备。

在第二项服务上,我使用 WebClient 访问第一项服务并从中接收数据。

我有两个选择,但它们对我不起作用。

如果两种服务都还活着,则然后一切正常。 如果第一个服务不可用,那么当我尝试通过 WebClient 发送请求时,什么都没有发生,我在浏览器中看到一个空白屏幕。

1)第一种选择:

@Service
public class WebClientService {

    private static final String API_MIME_TYPE = "application/json";
    private static final String API_BASE_URL = "http://localhost:8081";
    private static final String USER_AGENT = "User Service";
    private static final Logger logger = LoggerFactory.getLogger(WebClientService.class);

    private WebClient webClient;

    public WebClientService() {
        this.webClient = WebClient.builder()
                .baseUrl(API_BASE_URL)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, API_MIME_TYPE)
                .defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
                .filter(WebClientService.errorHandlingFilter()) 
                .build();
    }


     public Flux<Bucket> getDataByWebClient() {
        return webClient
                .get()
                .uri("/getAll")
                .exchange()
                .flatMapMany(clientResponse -> clientResponse.bodyToFlux(Bucket.class));
    }

    public static ExchangeFilterFunction errorHandlingFilter() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            if(clientResponse.statusCode()!=null && (clientResponse.statusCode().is5xxServerError() || clientResponse.statusCode().is4xxClientError()) ) {
                return clientResponse.bodyToMono(String.class)
                        .flatMap(errorBody -> {
                            return Mono.error(new MyCustomServerException());
                        });
            }else {
                return Mono.just(clientResponse);
            }
        });
    }

}

MyCustomServerException

public class MyCustomServerException extends Throwable {

    public String getAllEmployeesList() {
        return "Server error";
    }

    public MyCustomServerException() {
        getAllEmployeesList();
    }

}

2)第二个选项:

@Service
public class WebClientService {

    private static final String API_MIME_TYPE = "application/json";
    private static final String API_BASE_URL = "http://localhost:8081";
    private static final String USER_AGENT = "User Service";
    private static final Logger logger = LoggerFactory.getLogger(WebClientService.class);

    private WebClient webClient;

    public WebClientService() {
        this.webClient = WebClient.builder()
                .baseUrl(API_BASE_URL)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, API_MIME_TYPE)
                .defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
                .build();
    }

    public Flux<Bucket> getDataByWebClient() {
        return webClient
                .get()
                .uri("/stream/buckets/delay")
                .exchange()
                .flatMapMany(clientResponse -> clientResponse.bodyToFlux(Bucket.class));
    }


    public Flux<Bucket> getDataByWebClient() {
        return webClient
                .get()
                .uri("/getAll")
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, response -> {
                    System.out.println("4xx eror");
                    return Mono.error(new RuntimeException("4xx"));
                })
                .onStatus(HttpStatus::is5xxServerError, response -> {
                    System.out.println("5xx eror");
                    return Mono.error(new RuntimeException("5xx"));
                })

                .onStatus(HttpStatus::isError, clientResponse -> {
                    System.out.println("eror");
                    return Mono.error(new MyCustomServerException());
                })
                .bodyToFlux(Bucket.class);
    }

}

为什么这不起作用?谁能告诉我?

我希望浏览器显示班上出现错误的消息“ Server error”。

谢谢!

0 个答案:

没有答案