在Reactor的功能管道中向下传递对象

时间:2018-12-02 19:30:11

标签: rx-java reactive-programming project-reactor

我是反应堆和反应式编程的新手,我正在尝试解决以下情况。

我收到了来自Kafka主题的对象流,对于该流中的每个记录,我需要调用2个服务并验证对象。

public void consume(Flux<Data> flux)
{
flux.map(data->callRESTService1(data)).map(...<I need the data once again here to call rest service 2>
}

现在我正在使用以下样式来实现此目的,但是有没有更好/正确的方法来做到这一点?

public void consume(Flux<Data> flux)
{
   flux.subscribe(data->handleData(data));
}


 public void handleData(data)
    {
 Flux.concat(callRestService1(data),callRestService2(data)).reduce(data,reduce());
    }

此外,如果一项服务关闭,则我需要在侦听器上传播错误,以便不确认该消息,但在另一种情况下,如果验证失败,则需要将消息发布到另一个主题。

2 个答案:

答案 0 :(得分:0)

这两个路径都需要原始元素,并且每个路径都有不同的错误处理方式,这很好地表明您可能希望使用flatMap

Flux<Data> source; //= ...
return source.flatMap(value -> {
    Mono<IgnoreMe1> service1 = callRestService1(value);
    Mono<IgnoreMe2> service2 = callRestService2(value)
        .onErrorResume(e -> postErrorToTopic(e, value)); //might need some type massaging, eg. if the post to topic method returns a `Mono<Void>`

    //wait for the two to complete, propagate their errors if any, else return original value
    return Mono.when(service1, service2)
       .thenReturn(value);
}

答案 1 :(得分:0)

您可以尝试在这样的平面地图中进行压缩

Event 02

})