【发布时间】:2019-06-21 15:10:36
【问题描述】:
如何创建一个只保留 最新 n 个元素的EmitterProcessor,这样即使没有订阅者也能正常工作?
目前我创建了一个这样的处理器:
EmitterProcessor<Integer> processor = EmitterProcessor.create();
外部系统全天随机提供温度更新。在来自该系统的回调中,我这样做:
void tempConsumer(int temp) {
processor.onNext(temp);
}
但是,一旦添加了 processor.getBufferSize() 元素,onNext(...) 就会阻塞。
如何创建一个处理器来丢弃最旧的元素,在这种情况下,而不是阻塞?
reactor-core #763 似乎在某种程度上涵盖了这一点。 Simon Baslé 首先讨论了proposed change 到EmitterProcessor,这样当“在没有订阅者的情况下发送数据[并且] 队列包含bufferSize 元素时,最旧的元素将被丢弃,onNext 被加入队列。”但是在下一条评论中,他说“我们不会继续我上面建议的更改。我们建议您使用sink() 而不是直接使用onNext。也就是说,在内部使用onRequest 回调sink() 执行与请求一样多的 sink.next(...)。"
但是,如果我理解正确,这仅涵盖您可以按需计算新元素的情况,例如像这样:
FluxSink<Integer> sink = processor.sink();
Random random = new Random();
sink.onRequest(n -> random.nextInt()); // Generate next n requested elements.
但在我的情况下,我无法按需生成最新的 n 个温度读数。当然,我可以维护自己的最新读数的外部有界缓冲区,然后从 onRequest(...) 中读取,但我假设 Reactor 可以为我做到这一点?
我认为这个问题是重复的 - 但我的 Google foo 在这里让我失望了。
Ricard Kollcaku 的answer 应该使用ReplayProcessor 似乎是正确的做事方式。这是我写的另一个例子,目的是让我清楚如何使用它:
ReplayProcessor<Integer> flux = ReplayProcessor.create(Queues.SMALL_BUFFER_SIZE);
FluxSink<Integer> sink = flux.sink();
// ReplayProcessor.getBufferSize() returns unbounded,
// while CAPACITY returns the capacity of the underlying buffer.
int capacity = flux.scan(Scannable.Attr.CAPACITY);
// Add twice as many elements as the underlying buffer can take.
int count = capacity * 2;
for (int i = 0; i < count; i++) {
sink.next(i);
}
// If `capacity` is 256, this will print value 256 thru to 511.
flux.subscribe(System.out::println);
我还在Hands-On Reactive Programming with Reactor 中找到了this section,对解释事情很有用。
【问题讨论】:
-
您没有指定新订阅者的预期行为。 FWIW:
cache()是等价于ReplayProcessor的运算符。 -
ReplayProcessor似乎做我想做的事。新订阅者应该在订阅之前收到最后添加的 n 个元素,然后再接收新元素。对我来说真正重要的是,向通量添加新元素的回调不应该在调用next时阻塞,并且底层缓冲区不应该以无限制的方式增长,无论是否有订阅者。订阅者甚至可以接受“丢失”元素,即错过温度读数,如果它们消耗的速度不够快。
标签: java project-reactor eventemitter