简体   繁体   English

如何正确使用Reactor Publisher

[英]How to properly use a Reactor Publisher

I can´t figure out how to properly implement a Publisher/Subscriber scenario with Reactor. 我无法弄清楚如何使用Reactor正确实现发布者/订阅者场景。 I have a working solution, but the implementation does not seem correct to me: 我有一个可行的解决方案,但是对我来说实现似乎不正确:

My problem is that I need to manually implement the publisher to register the subscriber and pass the events: 我的问题是我需要手动实现发布者来注册订阅者并传递事件:

public void publishQuotes(String ticker) throws InterruptedException {

// [..] Here I generate some "lines" to be publisher

for (Subscriber<? super String> subscriber : subscribers) {
    lineList.forEach(line -> subscriber.onNext(line));
}

}

@Override
public void subscribe(Subscriber<? super String> subscriber) {
    subscribers.add(subscriber);

}

Then, I have a WorkQueue Processor (that should be the consumer): 然后,我有一个WorkQueue Processor(应该是使用者):

WorkQueueProcessor<String> sink = WorkQueueProcessor.create();

// Here I subscribe to my publiser
publisher.subscribe(sink);

// Creates a Reactive Stream from the processor (having converted the lines to Quotations)
Flux<StockQuotation> mappedRS = sink.map(quotationConverter::convertHistoricalCSVToStockQuotation);

// Here I perform a number of stream transformations 

// Each call to consume will be executed in a separated Thread
filteredRS.consume(i -> System.out.println(Thread.currentThread() + " data=" + i));

It works fine but is ugly as hell. 它工作正常,但很难受。 In this example taken from the Spring Guides, they use an EventBus to route the events from the publisher to the consumer but, when I try to link it with my processor I get this compiler error: 摘自Spring Guides的此示例中,他们使用EventBus将事件从发布者路由到使用者,但是当我尝试将其与处理器链接时,出现此编译器错误:

eventBus.on($("quotes"),sink);

The method on(Selector, Consumer<T>) in the type EventBus is not applicable for the arguments (Selector<String>, WorkQueueProcessor<String>)

I´m lost here, what would be the best way to link a publisher with a Processor? 我在这里迷路了,将发布者与处理者联系起来的最佳方法是什么? Would you recommend using an EventBus? 您会建议使用EventBus吗? If so, what would be the proper invokation? 如果是这样,什么是正确的发票?

Thanks! 谢谢!

If you use the EventBus, you will publish your lines via 如果您使用EventBus,则将通过以下方式发布行

 eventBus.notify("quotes", Event.wrap(line);

And subscribe via 并通过订阅

eventBus.on($("quotes"), e -> System.out.println(Thread.currentThread() + " data=" + e);

where "e" is of Type Event<String>. 其中“ e”的类型为事件<String>。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM