如何设计一个可复用的全局通知系统?
解读
面试官问“全局通知系统”并不是让你写个 Toast,而是想看你对 Vaadin 服务器端状态广播、UI 推送、线程安全、组件解耦、主题一致性、国际化、可测试性等企业级痛点的综合掌控力。国内项目普遍要求“开箱即用、零前端代码、能插拔、能灰度”,因此答案必须围绕 Vaadin 的以下核心机制展开:VaadinSession + UI.access() + Broadcaster + Spring 事件总线 + 自定义组件封装。同时,要体现你对国产环境(Spring Cloud Alibaba、Nacos、灰度发布、多租户)的落地经验。
知识点
- Vaadin 推送机制:@Push + PushMode.MANUAL / AUTOMATIC,以及 long-polling 与 WebSocket 在国内 NAT 网络下的选型。
- 服务器端广播:使用线程安全的 Broadcaster(基于 ExecutorService + WeakReference)或 Spring ApplicationEventPublisher。
- UI 线程安全:所有组件更新必须通过 UI.access() + ui.push(),否则在并发推送时会出现“IllegalStateException: UI not attached”。
- 自定义组件:通过 Composite 或 Lit 模板封装 Notification,支持类型(info/warning/error/success)、持续时间、可关闭、可点击回调。
- 主题与国际化:利用 Lumo 主题变量与 @I18NProvider,支持深色模式与中文文案。
- 插拔式配置:通过 Spring Boot Starter + @ConditionalOnProperty 实现“一键开关”,支持多租户隔离(TenantBroadcaster)。
- 灰度与限流:结合 Alibaba Sentinel,在 Broadcaster 层面对消息类型做 QPS 限流,防止大促期间“弹窗风暴”。
- 测试:使用 Vaadin TestBench + SpringBootTest + @AutoConfigureMockMvc 对推送链路做端到端压测,确保 1000 并发下内存不泄漏。
答案
设计分四层:接口层、广播层、UI 层、配置层,全部用 Java 完成,零 HTML/JS。
-
接口层 public interface GlobalNotification { enum Level { INFO, WARN, ERROR, SUCCESS } void send(String tenant, Level level, String key, Object... args); }
-
广播层(线程安全 + 多租户) @Component public class TenantBroadcaster { private final Map<String, Set<Consumer<NotificationEvent>>> listeners = new ConcurrentHashMap<>(); private final ExecutorService executor = Executors.newCachedThreadPool(new CustomizableThreadFactory("vaadin-push-")); public void register(String tenant, Consumer<NotificationEvent> consumer) { listeners.computeIfAbsent(tenant, k -> ConcurrentHashMap.newKeySet()).add(consumer); } public void broadcast(String tenant, NotificationEvent event) { Set<Consumer<NotificationEvent>> set = listeners.get(tenant); if (set != null) { set.removeIf(c -> c == null); set.forEach(c -> executor.execute(() -> c.accept(event))); } } }
-
UI 层(自动订阅 + 自动卸载) public class GlobalNotificationComponent extends Composite<VerticalLayout> { private final String tenant; private Consumer<NotificationEvent> listener; public GlobalNotificationComponent(String tenant) { this.tenant = tenant; setId("global-notification-holder"); // 方便 TestBench 定位 } @Override protected void onAttach(AttachEvent attachEvent) { UI ui = attachEvent.getUI(); listener = event -> ui.access(() -> { Notification notification = new Notification( event.getI18nMessage(), 5000, event.getLevel() == ERROR ? NotificationVariant.LUMO_ERROR : NotificationVariant.LUMO_SUCCESS); notification.setPosition(Notification.Position.TOP_END); notification.open(); ui.push(); }); VaadinSpringUtils.getBean(TenantBroadcaster.class).register(tenant, listener); } @Override protected void onDetach(DetachEvent detachEvent) { // 防止内存泄漏 VaadinSpringUtils.getBean(TenantBroadcaster.class).unregister(tenant, listener); } }
-
配置层(Spring Boot Starter) @Configuration @ConditionalOnProperty(name = "vaadin.notification.enabled", matchIfMissing = true) public class GlobalNotificationAutoConfiguration { @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public GlobalNotificationComponent globalNotificationComponent(VaadinRequest request) { String tenant = TenantContextHolder.get(); // 从网关透传 header return new GlobalNotificationComponent(tenant); } @Bean public GlobalNotification globalNotification(TenantBroadcaster broadcaster) { return (t, l, k, a) -> { String msg = I18nUtils.get(t, k, a); broadcaster.broadcast(t, new NotificationEvent(l, msg)); }; } }
使用:在任意 Service 中注入 GlobalNotification,调用 send 即可;前端无需代码,系统启动后自动挂载 GlobalNotificationComponent 到 MainLayout。
拓展思考
- 如果企业要求“离线推送”,可结合 PWA + Background Sync,在 Service Worker 里缓存未读消息,等网络恢复后一次性弹出;Vaadin 端只需暴露 /api/notification/offline 接口,返回 JSON,由 SW 调用。
- 对于“千人千面”的审批流场景,可在 NotificationEvent 里带上 route 参数,用户点击后自动导航到对应审批页面,实现“通知即入口”。
- 国内信创环境需适配国产中间件(东方通 TongWeb),此时 WebSocket 可能不可用,可回退到 long-polling,并在 Broadcaster 层做自适应切换。
- 审计合规:在 broadcast 前把事件写入 MongoDB,包含 tenant、user、IP、消息内容,方便后续等保 2.0 审查。
- 性能调优:当单租户在线 UI 超过 5000 时,可将 TenantBroadcaster 改造为 Redis Pub/Sub 广播,Vaadin 节点只订阅本机感兴趣租户,降低 JVM 内内存压力。