使用FluxProcessor 和FluxSink“动态”发布
手动向Flux 提供数据的技术之一是使用FluxProcessor#sink 方法,如下例所示
@SpringBootApplication
@RestController
public class DemoApplication {
final FluxProcessor processor;
final FluxSink sink;
final AtomicLong counter;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public DemoApplication() {
this.processor = DirectProcessor.create().serialize();
this.sink = processor.sink();
this.counter = new AtomicLong();
}
@GetMapping("/send")
public void test() {
sink.next("Hello World #" + counter.getAndIncrement());
}
@RequestMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent> sse() {
return processor.map(e -> ServerSentEvent.builder(e).build());
}
}
在这里,我创建了DirectProcessor 以支持多个订阅者,它将监听数据流。此外,我还提供了额外的 FluxProcessor#serialize,它为多生产者提供了安全支持(从不同线程调用而不违反 Reactive Streams 规范规则,尤其是 rule 1.3)。最后,通过调用“http://localhost:8080/send”我们会看到消息Hello World #1(当然,前提是你之前连接到了“http://localhost:8080”)
Reactor 3.4 更新
在 Reactor 3.4 中,您有一个名为 reactor.core.publisher.Sinks 的新 API。 Sinks API 为手动数据发送提供了一个流利的构建器,它允许您指定诸如流中的元素数量和背压行为、支持的订阅者数量和重放功能:
@SpringBootApplication
@RestController
public class DemoApplication {
final Sinks.Many sink;
final AtomicLong counter;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public DemoApplication() {
this.sink = Sinks.many().multicast().onBackpressureBuffer();
this.counter = new AtomicLong();
}
@GetMapping("/send")
public void test() {
EmitResult result = sink.tryEmitNext("Hello World #" + counter.getAndIncrement());
if (result.isFailure()) {
// do something here, since emission failed
}
}
@RequestMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent> sse() {
return sink.asFlux().map(e -> ServerSentEvent.builder(e).build());
}
}
注意,通过Sinks API 发送消息引入了emission 的新概念及其结果。这种 API 的原因是 Reactor 扩展了 Reactive-Streams 并且必须遵循背压控制。也就是说,如果您emit 的信号比请求的多,并且底层实现不支持缓冲,则您的消息将不会被传递。因此,tryEmitNext 的结果返回了EmitResult,表示消息是否已发送。
另外,请注意,默认情况下Sinsk API 提供了Sink 的序列化版本,这意味着您不必关心并发性。但是,如果您事先知道消息的发送是串行的,您可以构建一个不序列化给定消息的Sinks.unsafe() 版本