【问题标题】:Flux.create() not generating eventsFlux.create() 不生成事件
【发布时间】:2020-11-17 01:40:18
【问题描述】:

我正在尝试使用 Flux 通过 Flux.create 生成异步服务器发送事件。当我的客户连接请求时,最终会超时而没有收到任何事件。我在 Flux.create 发送的事件中硬编码只是为了查看数据流,但客户端仍然没有收到任何内容。

@GetMapping(path = "/stream", headers = "Accept=*/*", consumes = MediaType.ALL_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<PricingDTO>> getEventStream() {

  final Flux<ServerSentEvent<PricingDTO>> flux = Flux.<ServerSentEvent<PricingDTO>>create(emitter -> {
    final PricingDTO pricing = new PricingDTO();
    pricing.setId(99L);
    emitter.next(ServerSentEvent.builder(pricing).build());
  });

  return flux;
}

客户端(Angular)代码:

const eventSource = new EventSource(url);
eventSource.onmessage = (event) => {
  console.debug('Received event: ' + event);
  const json = JSON.parse(event.data);
  // Should be PricingDTO record here
};

eventSource.onerror = (error) => {
  if (eventSource.readyState === EventSource.CLOSED) {
    console.log('The stream has been closed by the server.');
    eventSource.close();
  } else {
    console.log('Error here: ' + error);
  }
};

我从来没有看到任何事件通过 EventSource。最终请求超时,我看到错误:net::ERR_EMPTY_RESPONSE

我是使用 WebFlux 的新手,我怀疑在返回 Flux 结果之前我错过了 FluxStream 上的一些初始化。我已经调试并确实看到我的 Web 服务正在接收请求并返回 Flux 对象。知道为什么我没有收到我的活动吗?

【问题讨论】:

    标签: spring spring-webflux eventsource


    【解决方案1】:

    您的 webflux 代码看起来不错。我使用以下简化示例(没有您的自定义类)对此进行了测试。

    @SpringBootApplication
    @RestController
    public class App {
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    
        @GetMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<String> getEventStream() {
            return Flux.create(emitter -> emitter.next("hi").next("hi2"));
        }
    }
    

    当连接到 chrome 中的 Steam 时,您可以看到事件正常进行:

    data:hi
    
    data:hi2
    

    问题要么在于您的接受标头过滤器,要么在于客户端。您当然可以通过在浏览器中连接到您的流(或者更好的是测试)来验证这一点

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多