通过 Flux.create
方法以编程方式创建了一个通量:
Flux<Tweet> flux = Flux.<Tweet>create(emitter -> ...);
有一个休息控制器:
@RestController
public class StreamController {
...
@GetMapping("/top-words")
public Flux<TopWords> streamTopWords() {
return topWordsStream.getTopWords();
}
}
有几个Web客户端(在独立进程中):
Flux<TopWords> topWordsFlux = WebClient.create(".../top-words")
.method(HttpMethod.GET)
.accept(MediaType.TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux(TopWords.class)
.subscribe(System.out::println);
JavaScript中有几个EventSource实例:
var eventSource = new EventSource(".../top-words");
eventSource.onmessage = function (e) {
console.log("Processing message: ", e.data);
};
只有前两个“订阅者”才会开始接收消息(无论是Web客户端还是EventSource实例) . 另一个将打开连接,获得HTTP 200状态,但事件流保持为空 . 客户端或服务器端都没有错误 .
我不明白,“2个订户”的限制在哪里 . 如果我想支持超过2个订阅者,我该怎么办?
该应用程序使用Spring Boot 2.0.0.RELEASE构建,并使用spring-boot-starter-webflux自动配置 . 默认配置不会更改 .
1 回答
我尝试适应的底层API存在限制(Twitter流API) .
目标是连接到Twitter一次,并处理各种不同订阅者的推文流 .
最初我认为传递给
Flux.create
方法的 Launcher 总是对所有订户使用相同的FluxSink
. 那当然没有意义 . 相反,每个用户提供FluxSink
,因为javadoc清楚地说明了 .我使用Twitter监听器实现了我的用例,允许注册(和取消注册)许多
FluxSink
实例 . 这样,单个推文流可以由各种不同的订户订阅 .我的
twitterListener
在spring-social-twitter项目中实现了org.springframework.social.twitter.api.StreamListener
.