从 Java 中的 Mono 获取对象

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

我有一个 SpringBoot 应用程序,它正在调用 WebClient 以返回 Mono 。我正在尝试从 Mono 中检索对象。我执行了下面的代码,并在这里查找了其他类似的问题,但无法得到解决方案。下面的代码在尝试将 Disposable 对象转换为 Employee 时出现 ClassCastException classreactor.core.publisher.LambdaMonoSubscriber 无法转换为类 com.example.SpringBootReactiveClient.entity.Employee。请建议我如何获取 Employee 对象。


Controller
----------------

 //http://localhost:8383/rxc/v1/getEmployeeByIdAsyncAndExecute/11351
    @GetMapping(value = "/getEmployeeByIdAsyncAndExecute/{id}", produces = "application/json")
    public Employee getEmployeeByIdAsyncAndExecute(@PathVariable("id") Integer id) {
        Mono<Employee> employeeMono = springBootReactiveClientService.getEmployeeByIdAsync(id);
        return (Employee) employeeMono.flatMap(this::updateEmployee).subscribe();
    }

    private Mono<Employee> updateEmployee(Employee employee) {
        employee.setEmail("[email protected]");
        return Mono.just(employee);
    }

Service
----------------

 public Mono<Employee> getEmployeeByIdAsync(Integer id) {
        return webClient
                .method(HttpMethod.GET)
                .uri("http://localhost:9898/rx/getEmployeeById/" + id)
                .accept(MediaType.ALL)
                .contentType(MediaType.APPLICATION_JSON)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .retrieve()
                .bodyToMono(Employee.class);
    }

spring-boot mono spring-webflux
1个回答
0
投票

您遇到的 ClassCastException 是因为您尝试将 Mono 直接转换为 Employee,这不是您应该处理反应式操作结果的方式。在您的控制器中,您应该使用 Project Reactor 提供的反应式构造来正确处理数据。要获取 Employee 对象,您应该订阅 Mono,然后返回结果作为响应。这是更正后的代码:

    @GetMapping(value = "/getEmployeeByIdAsyncAndExecute/{id}", produces = "application/json")        
    public Mono<Employee> getEmployeeByIdAsyncAndExecute(@PathVariable("id") Integer id) {
        return springBootReactiveClientService.getEmployeeByIdAsync(id)
            .flatMap(this::updateEmployee);
    }

此外,请确保在整个应用程序中正确处理 Mono 和 Flux 类型,以利用响应式编程的优势。在使用外部服务或数据库时,您的服务和数据层还应该返回反应类型。

© www.soinside.com 2019 - 2024. All rights reserved.