spring-boot - 如何在spring boot webFlux中为特定用户实现服务器发送事件
问题描述
如何在spring boot webFlux中为特定用户实现服务器发送事件例如:-我需要按用户发送事件而不是广播
解决方案
您可以使用 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);
}
这将创建EmitterProcessor
and 过滤器的共享实例,以便只有与给定目标匹配的值才会到达。
现在,您可以在其他地方使用以下代码将事件发送到特定用户(或本例中的目的地):
events.onNext(new Event(destination, "Hello world!!"));
推荐阅读
- swift - self.init() 导致便利 init(){ } 无限运行
- angular - 构建 Angular 谷歌地图 AGM 时出错
- c++ - 根据用户输入的玩家数量创建玩家对象?
- java - 如何在 Java 中使用正则表达式从符号中提取内容?
- java - 在 Java 8 中使用线程和 lambda 按顺序打印数字
- python-3.x - 当我输入大量数据时,为什么我的简单代码要花这么多时间来执行?
- python - pyqt5 中的 Python 代码输出错误的值
- google-apps-script - 使用脚本编辑器将脚本嵌入 Google 幻灯片
- excel - Apache POI - 删除外部书籍参考
- python - 如何从组件中获取 Kubeflow 管道运行名称?