【问题标题】:Iterating through Flux <T> and fetching data with Webclient遍历 Flux <T> 并使用 Webclient 获取数据
【发布时间】:2019-12-14 21:02:54
【问题描述】:

我正在尝试从另一个微服务中获取数据。假设您有三个微服务:State、School 和 Student。您通过来自 SchoolRepository 的 stateId 获得 Flux,并且对于每个 School,您通过 webclient 调用 Student 微服务,该 Webclient 返回 Flux 并将其设置为 Flux。很快,我想做的是:

public Flux<School> getBySchool(Long stateId){

        Flux<School> schoolList=schoolRepository.findByStateId(stateId);
        //And for each school I want to do this
                Flux<Student> studentsfound=webClient.get().uri("bla bla bla"+school.getSchoolId).exchange().flatMapMany(response->response.bodyToFlux(Student.class));
                //I have a List<Student> entity in School domain, so I want Flux<Student> --> List<Student> and add it to School. Something like school.setStudentList(studentListReturned).
        //And then return Flux<Stundent>
}

如何遍历 Flux ,获得 Flux 后如何将其添加到适当的 Flux ?提前谢谢你。

更新

解决方案

非常感谢@K.Nicholas。我能够解决以下问题,但欢迎使用更优雅的解决方案。我在控制器中订阅了 schoolList,因为我必须将 Flux 从服务层返回到控制器层。

public Flux<School> getBySchoolWithStudents(Long stateId) {
    Flux<School> schoolList = schoolRepository.findByStateId(stateId);
    return schoolList.flatMap(school -> {
        Flux<Student> studentFlux = webClientBuilder.build().get().uri(REQUEST_URI + school.getSchoolId()).exchange().flatMapMany(response -> response.bodyToFlux(Student.class));
        return studentFlux.collectList().map(list -> {
            school.setStudentList(list);
            return school;
        });
    });
}

【问题讨论】:

    标签: reactive-programming spring-webflux


    【解决方案1】:

    编辑:第二次尝试。所以,没有什么特别的,我能看到。使用collectList 方法并在map 函数中分配它。 map 函数返回范围内的学校对象。我必须进行一些调试以确保我的类正确支持序列化/反序列化。

        WebClient.create().get().uri(URI.create("http://localhost:8082/ss/school?state=CA"))
        .accept(MediaType.APPLICATION_JSON)
        .exchange()
        .flatMapMany(cr->cr.bodyToFlux(School.class))
        .flatMap(school->{
            return WebClient.create().get().uri(URI.create("http://localhost:8081/ss/student?school="+school.getName()))
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .flatMapMany(crs->crs.bodyToFlux(Student.class))
            .collectList()
            .map(sl->{
                school.setStudents(sl);
                return school;
            });
        })
        .subscribe(System.out::println);
    

    【讨论】:

    • 感谢您的回复。当我尝试使用地图时,我没有从 webclient 获取数据。它实际上没有击中网址。我什至尝试在地图结束后订阅,但结果没有改变。所以,我尝试订阅。这次我可以获得数据,但内部订阅没有设置列表。我错过了什么?你能看看上面的更新吗?
    • 如果你有 response.bodyToFlux 我不明白你为什么需要 .flatMapMany。
    • 你有什么建议?如果我使用 flatMap,我会收到一条错误消息(必需类型:Flux 提供:Mono 不存在类型变量 R 的实例,因此 Mono 符合 Flux)你建议我使用retrieve吗?我会尝试,但问题是我已经在获取数据,但我不明白为什么我无法保存它们(即将其设置为 List)。您是否认为它与 webclient 相关,即我如何检索数据?
    • 谢谢您,您上次的编辑帮助很大。我更新了问题并添加了解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多