Java application: Sequence workflow pattern

情到浓时终转凉″ 提交于 2019-12-05 22:06:26

Even though you don't need non-blocking asynchronous calls right now, Reactor can still be a good fit for this because it is good at orchestrating that sort of processing pipeline. I'd argue Java 8 Stream could also fit the bill but is a little less powerful in that regard.

Expanding method references for clarity, and with a bit of guesswork on my part, your code would look like something like this in Reactor:

var response = Mono.just(initialArgs)
    .flatMap(args1 -> Mono.fromCallable(() -> step1.execute(args1))
        .map(result1 -> process(result1, args1) //args1 still in scope inside flatMap
    )
    .flatMap(args2 -> Mono.fromCallable(() -> step2.execute(args2))
    //alternatively to last flatMap, with caveat:
    //.map(args2 -> step2.execute(args2))
    .map(endResult -> new Response(endResult))
    .onErrorResume(error -> {
        Response errorResponse = new Response();
        errorResponse.setIsPartialSuccess(true);
        errorResponse.setPartialResults(error.getDetails());
        return Mono.just(errorResponse);
    })
    .block();

Operators used in this particular chain don't change threads, so this would all execute in the thread from which the last block() method is called.

Errors from any step stop the whole processing and are propagated to the end (block() would then throw the exception).

Note that some operators (mostly those that have a notion of time) change threads, and at this point stepX.execute being blocking becomes a problem because that would block threads that are supposed to be shared by the whole of Reactor code (not only a particular processing pipeline) and are limited resources.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!