Spring 带有 DeferredResult 和 Reactor 的异步 REST

Spring Asynchronous REST with DeferredResult and Reactor

为了可用性,这是我能详细说明的最好的想法,以便在 REST 调用中获得 Reactor 的异步性:我不满意..关于如何做得更好的任何想法?

(complete code here for reference)

REST 接口:

@RestController
public class REST_Interface {

    @Autowired
    public EventBus eventBus;

    @RequestMapping("/getGreeting/{name}")
    public DeferredResult<String> getGreeting(@PathVariable String name) {

        DeferredResult<String> result = new DeferredResult<>();

        EventWrapper<String> wrapper = new EventWrapper<>(result, name);
        eventBus.notify("greeting.topic", Event.wrap(wrapper));

        return result;
        }
}

EventWrapper:

public class EventWrapper<T> {
    private DeferredResult<T> deferredResult;
    private T payload;

    public EventWrapper(DeferredResult<T> deferredResult, T payload) {
        this.deferredResult = deferredResult;
        this.payload = payload;
    }
    // Getters & Setters
}

事件消费者:

@Consumer
public class EventConsumer {

    @Autowired
    public EventBus eventBus;

    @Selector("greeting.topic")
    public void onTestTopic(Object o) {
        System.out.println("Event receved for Logging " + o.toString());
    }

    @Selector("greeting.topic")
    public void wrappedGreeter(EventWrapper<String> ew) {

        ew.getDeferredResult().setResult("Ciao " + ow.getPayload().toUpperCase());
    }
}

看看 EventBus.sendAndReceive(),它正是为这种用例而设计的。来自 http://projectreactor.io/docs/reference/#bus-request-reply 的示例:

EventBus bus;

bus.receive($("job.sink"), (Event<String> ev) -> {
  return ev.getData().toUpperCase();
}); 

bus.sendAndReceive(
    "job.sink",
   Event.wrap("Hello World!"),
   s -> System.out.printf("Got %s on thread %s%n", s, Thread.currentThread())
);