将 Java WebFlux 转换为 Spring MVC

问题描述 投票:0回答:1

由于内部需要,我需要将项目从 Spring Reactive WebFlux 转换为 Spring MVC。

有人可以帮助我了解使用 Spring MVC 更好的解决方案中做到这一点的最佳方法吗?

    private Flux<CoreErrorResponse> myMethodName() {
        return webClient.get()
            .uri(buildListErrorsUrl().toUriString())
            .retrieve()
            .bodyToFlux(CoreErrorResponse.class)
            .doOnError(e -> log.error("failed: {}", e.getMessage()))
            .onErrorResume(e -> Flux.empty())
            .timeout(Duration.ofSeconds(readTimeOutTranslateList), Flux.empty());
    }
    public Mono<MyClassErrorResponse> findMonoMyError(final String token, final MyClassResponse myclass) {
        return Mono.just(finError(myclass));
    }

这将是最合适的解决方案?


import org.springframework.web.client.RestTemplate;
import java.util.Collections;
import java.util.List;

public class MyService {

    private final RestTemplate restTemplate;

    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    private List<CoreErrorResponse> myMethodName() {
        try {
            // Assuming `buildListErrorsUrl()` returns a URI string, so you may need to convert it to a URL.
            String url = buildListErrorsUrl().toUriString();
            return Arrays.asList(restTemplate.getForObject(url, CoreErrorResponse[].class));
        } catch (RestClientException e) {
            log.error("failed: {}", e.getMessage());
            return Collections.emptyList(); // Return an empty list in case of error
        }
    }
}

spring-mvc spring-webflux
1个回答
0
投票

您可以使用 Completable future 来考虑超时。所以你的代码看起来像:

public List<CoreErrorResponse> myMethodName() {
    try {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return restTemplate.exchange(
                        buildListErrorsUrl().toUriString(),
                        HttpMethod.GET,
                        null,
                        new ParameterizedTypeReference<List<CoreErrorResponse>>() {}
                ).getBody();
            } catch (Exception e) {
                log.error("Request failed: {}", e.getMessage());
                return Collections.emptyList();
            }
            // ensure timeout 
        }).get(readTimeoutSeconds, TimeUnit.SECONDS);

    } catch (Exception e) {
        log.error("Request failed or timed out: {}", e.getMessage());
        return Collections.emptyList();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.