java - Spring reactive - 接收新消息的事件

标签 java spring spring-mvc reactive-programming spring-webflux

我有一个带有 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/

相关文章:

java图像加载与效果

java - 具有子类泛型的子类

spring - 为什么 setDisallowedFields 为 id? -- Spring 宠物诊所示例

java - Spring 需要的 CassandraTemplate.execute 批处理语句帮助

javascript - 为什么没有对 spring Controller 进行 ajax 调用 我应该做什么更改?

javascript - 在jsp中更新数据列表

java - JMSTemplate send() 回滚或超时

java - Java 类中的 Grails @Autowire 不起作用

java - 在 Heroku 中部署 Spring Angular2 应用程序时出错

Spring:@Autowired 用于 POJO,不由 Spring 管理