如何实现服务器在 Spring 引导 webFlux 中为特定用户发送的事件例如:- 我需要根据用户发送事件而不是广播
您可以使用
EmitterProcessor
向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);
}
这将创建EmitterProcessor
和筛选器的共享实例,以便只有与给定目标匹配的值才会到达。
现在,您可以在其他位置使用以下代码将事件发送到特定用户(在本例中为目标(:
events.onNext(new Event(destination, "Hello world!!"));