diff --git a/src/main/java/com/webgame/webgamebackend/common/event/SseEvent.java b/src/main/java/com/webgame/webgamebackend/common/event/SseEvent.java new file mode 100644 index 0000000..e8892fc --- /dev/null +++ b/src/main/java/com/webgame/webgamebackend/common/event/SseEvent.java @@ -0,0 +1,50 @@ +package com.webgame.webgamebackend.common.event; + +import jakarta.annotation.Nullable; + +/** + * SSE 事件模型(不可变 record) + * + * @param id 事件唯一 ID,格式 "evt_{timestamp}_{random}" + * @param type 事件类型 + * @param targetId 目标用户 accountId,null 表示广播给所有在线用户 + * @param data 事件携带的 JSON 数据 + * @param timestamp 事件时间戳(毫秒) + */ +public record SseEvent( + String id, + SseEventType type, + @Nullable String targetId, + String data, + long timestamp +) { + /** + * 创建广播事件(无特定目标用户) + * + * @param type 事件类型 + * @param data JSON 数据字符串 + * @return SseEvent 实例 + */ + public static SseEvent broadcast(SseEventType type, String data) { + long now = System.currentTimeMillis(); + return new SseEvent("evt_" + now + "_" + randomSuffix(), type, null, data, now); + } + + /** + * 创建定向事件(推送给特定用户) + * + * @param type 事件类型 + * @param targetId 目标用户 accountId + * @param data JSON 数据字符串 + * @return SseEvent 实例 + */ + public static SseEvent targeted(SseEventType type, String targetId, String data) { + long now = System.currentTimeMillis(); + return new SseEvent("evt_" + now + "_" + randomSuffix(), type, targetId, data, now); + } + + /** 生成 6 位随机后缀 */ + private static String randomSuffix() { + return String.format("%06x", (long) (Math.random() * 0xFFFFFF)); + } +} diff --git a/src/main/java/com/webgame/webgamebackend/common/event/SseEventType.java b/src/main/java/com/webgame/webgamebackend/common/event/SseEventType.java new file mode 100644 index 0000000..f4a0f9d --- /dev/null +++ b/src/main/java/com/webgame/webgamebackend/common/event/SseEventType.java @@ -0,0 +1,28 @@ +package com.webgame.webgamebackend.common.event; + +/** + * SSE 事件类型枚举 + *

+ * ROOM_CREATED / ROOM_UPDATED / ROOM_REMOVED 为广播事件(推送给所有在线用户) + * KICKED / GAME_STARTED / BALANCE_CHG 为定向事件(推送给特定用户) + */ +public enum SseEventType { + + /** 新房间创建(广播) */ + ROOM_CREATED, + + /** 房间状态更新:玩家加入/离开、准备切换、房主变更、游戏开始等(广播) */ + ROOM_UPDATED, + + /** 房间移除:无人散场或游戏结束关闭(广播) */ + ROOM_REMOVED, + + /** 被房主踢出房间(定向) */ + KICKED, + + /** 你所在的房间游戏已开始(定向) */ + GAME_STARTED, + + /** 余额变动通知(定向) */ + BALANCE_CHG +}