如何在 Reactive Programming 中实现 Hot Stream

How to implement Hot Stream in Reactive Programming

根据 Reactive Stream 范式,

Currently, we’ve focused primarily on cold streams. These are static, fixed length streams which are easy to deal with. A more realistic use case for reactive might be something that happens infinitely. For example, we could have a stream of mouse movements which constantly needs to be reacted to or a twitter feed. These types of streams are called hot streams, as they are always running and can be subscribed to at any point in time, missing the start of the data.

那么如何实现这个热流呢?

这可以使用 ConnectableFlux 完成,如下所示:

ConnectableFlux<Object> publish = Flux.create(fluxSink -> {
    while(true) {
        fluxSink.next(System.currentTimeMillis());
    }
})
  .publish();

您可以使用 MongoDB 的 Capped Collections 创建热流。通过在该集合上使用 @Tailable ,它将创建一个发布每个新条目的发布者。使用 .share() 它将多播该发布者,因此并非每个订阅都会创建一个新的数据库连接。