首页 > 解决方案 > 如何在spring boot webFlux中为特定用户实现服务器发送事件

问题描述

如何在spring boot webFlux中为特定用户实现服务器发送事件例如:-我需要按用户发送事件而不是广播

标签: spring-boot

解决方案


您可以使用 anEmitterProcessor将新值添加到Flux. 例如:

 public class Event {
     private String destination;
     private String value;

     // Getters + Setters
 }

然后你可以有一个共享EmitterProcessor

private EmitterProcessor<Event> events = EmitterProcessor.create();

现在您可以使用控制器来订阅它:

@GetMapping(value = "/{destination}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> getEvents(@PathVariable String destination) {
    return events.share()
        .filter(event -> event.getDestination().equals(destination))
        .map(Event::getValue);
}

这将创建EmitterProcessorand 过滤器的共享实例,以便只有与给定目标匹配的值才会到达。

现在,您可以在其他地方使用以下代码将事件发送到特定用户(或本例中的目的地):

events.onNext(new Event(destination, "Hello world!!"));

推荐阅读