feat: 添加 SseEventType 枚举和 SseEvent record 事件模型

This commit is contained in:
2026-06-22 13:40:06 +08:00
parent 2467a5097c
commit 875f2bc073
2 changed files with 78 additions and 0 deletions

View File

@@ -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 目标用户 accountIdnull 表示广播给所有在线用户
* @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));
}
}

View File

@@ -0,0 +1,28 @@
package com.webgame.webgamebackend.common.event;
/**
* SSE 事件类型枚举
* <p>
* 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
}