我有一个带有 spring reactive webflux 的聊天应用程序。创建新消息时,所有订阅者都会收到该消息(这只是简化我的问题的示例)。一切都正确并且工作完美。但是,现在我需要在收到新消息时为订阅者设置一个事件。
这是我的代码:
Controller :
@Autowired
@Qualifier("ptpReplayProcessor")
private ReplayProcessor<String> ptpReplayProcessor;
@GetMapping(value = "/chat/subscribe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> subscribe() {
return Flux.from(ptpReplayProcessor);
}
重播处理器配置:
@Configuration
public class ReplayProcessorConfig {
@Bean("ptpReplayProcessor")
ReplayProcessor<String> ptpReplayProcessor() {
ReplayProcessor<String> replayProcessor = ReplayProcessor.create(0, false);
replayProcessor.subscribe(new BaseSubscriber<String>() {
@Override
protected void hookOnNext(String ptp) {
System.out.println("replay processor called!");
}
});
return replayProcessor;
}
}
pom.xml
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
创建新消息时,我调用 ptpReplayProcessor.onNext(message)
。这工作正常并且所有客户端都收到消息,但是短语 replay processor called!
只是从消息的发送者打印。我想在收到新消息时为所有客户引发一个事件。我还尝试了 ReplayProcessor.doOnNext()
和 ReplayProcessor.doOnEach()
方法,但没有成功。有没有办法做到这一点?
最佳答案
您可以在您的订阅方法中执行此操作:
return Flux.from(ptpReplayProcessor).doOnNext(s -> System.out.println("new message has been sent"));
关于java - Spring reactive - 接收新消息的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405278/