Spring 反应式 - 接收新消息时的事件

Spring reactive - event on receiveing new message

我有一个带有 spring 反应式 webflux 的聊天应用程序。创建新消息时,所有订阅者都会收到该消息(这只是简化我的问题的示例)。一切都正确并且工作完美。但是,现在我需要 当新消息到达时订阅者的事件。

这是我的代码:

控制器:

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

ReplayProcessorConfig:

@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"));