gpt4 book ai didi

java - Spring 异步 REST 与 DeferredResult 和 Reactor

转载 作者:行者123 更新时间:2023-12-02 04:10:24 32 4
gpt4 key购买 nike

这是我可以详细阐述的在 REST 调用中使用 Reactor 获得异步性的最佳想法,以提高可用性:我不满足......关于如何做得更好的任何想法?

(complete code here for reference)

REST 接口(interface):

@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;
}
}

事件包装器:

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())
);

关于java - Spring 异步 REST 与 DeferredResult 和 Reactor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854611/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com