首页 > 解决方案 > 响应式 WebFlux 向特定订阅者发布通知

问题描述

我想建立一个用户通知系统。想法是,如果用户已登录,系统将订阅通知服务,并且在为该用户生成通知时,它必须返回新通知的数量。

我正在使用带有 Webflux 的 Java Spring boot 来实现这一点。我能够构建一个基本示例,它使用 EmitterProcessor 工作,每次我添加通知时,它都会根据用户标识符向订阅者发送新通知的数量。

我运行应用程序并设置 1 个订阅者,假设用户 A,当我添加通知时,用户 A 收到更新,当我再添加 2 个订阅者(B 和 C)时,问题就开始了。当我为用户 A 创建通知时,用户 B 和 C 都会收到更新。

所以我的问题是,使用 webflux 有没有办法将通知更新直接发送给代表正确用户的订阅者?

我的代码基础如下:

通量处理器和通量接收器初始化

private final FluxProcessor processor;
private final FluxSink<Integer> sink;

public NotificationController() {

    this.processor = EmitterProcessor.create().serialize();
    this.sink = processor.sink();

}

订阅收件箱方法

@GetMapping(value = "/inbox/{userId}")
public Flux<ServerSentEvent> subscribeInbox(@PathVariable String userId) {

    Flux<ServerSentEvent> serverSentEventFlux = this.processor.map(e -> ServerSentEvent.builder(e).build());

    List<Notification> notificationList = this.repositoryMap.get(userId);
    if (notificationList == null) {
        notificationList = new ArrayList<>();
    }

    this.sink.next(notificationList.size());

    return serverSentEventFlux;

}

外部强制发布通知方式

@PostMapping(value = "/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity publishNotifications(@PathVariable String userId) {

    List<Notification> notificationList = this.repositoryMap.get(userId);
    if (notificationList == null) {
        notificationList = new ArrayList<>();
    }

    this.sink.next(notificationList.size());
    return ResponseEntity.ok().build();

}

提前致谢。

标签: javaspring-bootnotificationsspring-webfluxspring-reactive

解决方案


推荐阅读