Commit 6c687b75 authored by wujipeng's avatar wujipeng
Browse files

Merge remote-tracking branch 'origin/dev-v1.0' into dev-v1.0

parents 26d3f71b 6aa0dc38
package com.platform.business.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface NotificationAudienceMapper {
/** 查询全部未逻辑删除用户,用于全员广播。 */
List<String> selectAllActiveUserIds();
/** 通过手机号角色映射表解析角色接收人。 */
List<String> selectUserIdsByRoleNames(@Param("roleNames") List<String> roleNames);
/** 通过班级学员关系表解析班级接收人。 */
List<String> selectUserIdsByClassIds(@Param("classIds") List<Integer> classIds);
}
package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.dto.NotificationMessageQueryDTO;
import com.platform.business.model.entity.NotificationMessageEntity;
import com.platform.business.model.vo.NotificationMessageVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface NotificationMessageMapper extends BaseMapper<NotificationMessageEntity> {
/** 按event_id唯一索引忽略重复插入,实现消费端幂等。 */
int insertIgnore(NotificationMessageEntity message);
/** 通过事件ID读取已经存在的消息,兼容首次消费和重复消费。 */
NotificationMessageEntity selectByEventId(@Param("eventId") String eventId);
/** 查询当前用户未删除且未过期的消息列表。 */
List<NotificationMessageVO> queryUserMessages(NotificationMessageQueryDTO query);
/** 查询一条确实属于当前用户的消息,避免通过messageId越权读取。 */
NotificationMessageVO selectUserMessage(@Param("messageId") String messageId,
@Param("userId") String userId);
}
package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.entity.NotificationMessageRecipientEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
@Mapper
public interface NotificationMessageRecipientMapper extends BaseMapper<NotificationMessageRecipientEntity> {
/** 批量插入接收人;唯一键冲突时忽略,支持MQ重复投递。 */
int insertBatchIgnore(@Param("recipients") List<NotificationMessageRecipientEntity> recipients);
/** 仅更新属于指定用户且未删除的消息。 */
int markRead(@Param("messageId") String messageId, @Param("userId") String userId,
@Param("now") Date now);
/** 批量标记当前用户所有未读消息。 */
int markAllRead(@Param("userId") String userId, @Param("now") Date now);
/** 用户侧逻辑删除单条消息。 */
int logicalDelete(@Param("messageId") String messageId, @Param("userId") String userId,
@Param("now") Date now);
/** 用户侧逻辑删除全部已读消息。 */
int clearRead(@Param("userId") String userId, @Param("now") Date now);
/** 统计当前用户未删除、未读且未过期的消息数。 */
long unreadCount(@Param("userId") String userId);
/** 记录消息已经送达到目标节点上的至少一个本地WebSocket连接。 */
int markDelivered(@Param("userIds") List<String> userIds, @Param("messageId") String messageId,
@Param("now") Date now);
}
package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.entity.NotificationOutboxEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
@Mapper
public interface NotificationOutboxMapper extends BaseMapper<NotificationOutboxEntity> {
/** 查询到达计划时间且满足重试时间的候选记录;查询本身不代表取得处理权。 */
List<NotificationOutboxEntity> selectDue(@Param("now") Date now, @Param("limit") int limit);
/** 通过条件更新将NEW/RETRY原子切换为PUBLISHING,多实例中只有一个实例能成功。 */
int claim(@Param("id") String id, @Param("updatedAt") Date updatedAt);
/** Publisher Confirm成功后标记为已发布。 */
int markPublished(@Param("id") String id, @Param("publishedAt") Date publishedAt);
/** 发布失败后记录指数退避时间;达到上限时转为FAILED。 */
int markRetry(@Param("id") String id, @Param("retryCount") int retryCount,
@Param("nextRetryAt") Date nextRetryAt, @Param("lastError") String lastError,
@Param("failed") boolean failed, @Param("updatedAt") Date updatedAt);
/** 将因进程崩溃而长时间停留在PUBLISHING的记录恢复为RETRY。 */
int recoverStuck(@Param("staleBefore") Date staleBefore, @Param("updatedAt") Date updatedAt);
}
......@@ -10,12 +10,16 @@ import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/** 请假申请查询、并发审批及教师权限校验的数据访问接口。 */
@Mapper
public interface StudentLeaveApplicationMapper extends BaseMapper<StudentLeaveApplicationEntity> {
/** 按三端限定条件查询申请及申请人、审批人完整手机号。 */
List<LeaveApplicationVO> queryApplications(LeaveQueryDTO query);
/** 修改、撤回或审批前锁定申请主记录,避免状态被并发修改。 */
StudentLeaveApplicationEntity selectByIdForUpdate(@Param("id") String id);
/** 仅当申请仍为PENDING时写入审批结果,实现教师和管理员先处理者生效。 */
int reviewPending(@Param("id") String id,
@Param("status") String status,
@Param("approverId") String approverId,
......@@ -23,6 +27,7 @@ public interface StudentLeaveApplicationMapper extends BaseMapper<StudentLeaveAp
@Param("approvalOpinion") String approvalOpinion,
@Param("reviewedAt") Date reviewedAt);
/** 统计申请中由指定教师授课的关联课程,用于教师端数据权限校验。 */
int countTeacherRelatedSubjects(@Param("leaveId") String leaveId,
@Param("teacherId") String teacherId);
}
......@@ -8,7 +8,9 @@ import org.apache.ibatis.annotations.Param;
import java.util.List;
/** 请假申请与证明材料关联的数据访问接口。 */
@Mapper
public interface StudentLeaveAttachmentMapper extends BaseMapper<StudentLeaveAttachmentEntity> {
/** 查询申请关联且未被逻辑删除的文件信息。 */
List<LeaveAttachmentVO> queryAttachmentsByLeaveId(@Param("leaveId") String leaveId);
}
......@@ -8,7 +8,9 @@ import org.apache.ibatis.annotations.Param;
import java.util.List;
/** 请假申请与自动匹配课程关联的数据访问接口。 */
@Mapper
public interface StudentLeaveSubjectMapper extends BaseMapper<StudentLeaveSubjectEntity> {
/** 查询申请关联课程及班级、教师完整展示信息。 */
List<LeaveSubjectVO> querySubjectsByLeaveId(@Param("leaveId") String leaveId);
}
package com.platform.business.mq;
import com.platform.business.constant.NotificationConstants;
import com.platform.business.model.dto.NotificationEventDTO;
import com.platform.business.service.NotificationMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 消息持久化事件消费者。
*
* <p>正常消费由监听容器自动ACK。业务处理异常时不在当前队列立即重试,而是重新发布到30秒TTL队列;
* TTL到期后通过DLX回到事件交换机。超过最大次数进入死信队列,避免有毒消息形成无限热循环。</p>
*/
@Component
@Slf4j
public class NotificationEventConsumer {
private static final int MAX_RETRIES = 3;
@Resource
private NotificationMessageService messageService;
@Resource
private RabbitTemplate rabbitTemplate;
@RabbitListener(queues = NotificationConstants.EVENT_QUEUE)
public void consume(NotificationEventDTO event, Message rawMessage) {
try {
messageService.consume(event);
} catch (Exception e) {
int retries = retryCount(rawMessage);
log.error("消费消息事件失败: eventId={}, retry={}", event == null ? null : event.getEventId(), retries, e);
if (retries >= MAX_RETRIES) {
// 已达到上限:保留原事件和最终重试次数,供运维人员检查后人工重放。
rabbitTemplate.convertAndSend(NotificationConstants.DEAD_EXCHANGE,
NotificationConstants.DEAD_ROUTING_KEY, event,
message -> withRetryHeader(message, retries));
} else {
// 重试报文头由应用维护,TTL队列只负责延迟,不修改业务事件内容。
rabbitTemplate.convertAndSend(NotificationConstants.RETRY_EXCHANGE,
NotificationConstants.RETRY_ROUTING_KEY, event,
message -> withRetryHeader(message, retries + 1));
}
// 重新发布成功后正常返回,原消息由容器 ACK;发布失败则异常上抛并由 broker 重新投递原消息。
}
}
private Message withRetryHeader(Message message, int retries) {
message.getMessageProperties().setHeader(NotificationConstants.RETRY_HEADER, retries);
return message;
}
private int retryCount(Message message) {
// AMQP客户端可能把整数头反序列化成不同Number子类,因此统一按Number读取。
Object value = message.getMessageProperties().getHeaders().get(NotificationConstants.RETRY_HEADER);
return value instanceof Number ? ((Number) value).intValue() : 0;
}
}
package com.platform.business.mq;
import com.alibaba.fastjson2.JSON;
import com.platform.business.duplex.NotificationWebSocketServer;
import com.platform.business.mapper.NotificationMessageRecipientMapper;
import com.platform.business.model.dto.NotificationPushDTO;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/** 当前节点临时推送队列的消费者,负责把节点批量报文分发到本地WebSocket Session。 */
@Component
public class NotificationPushConsumer {
@Resource
private NotificationMessageRecipientMapper recipientMapper;
@RabbitListener(queues = "#{notificationPushQueue.name}")
public void push(NotificationPushDTO push) {
// 复制目标列表后立即清空DTO中的userIds,防止浏览器看到同批次其他用户标识。
List<String> targets = push.getUserIds() == null ? new ArrayList<>() : new ArrayList<>(push.getUserIds());
push.setUserIds(null);
String payload = JSON.toJSONString(push);
List<String> deliveredUsers = new ArrayList<>();
for (String userId : targets) {
if (NotificationWebSocketServer.sendToLocalUser(userId, payload) > 0) {
deliveredUsers.add(userId);
}
}
if (!deliveredUsers.isEmpty() && push.getMessageId() != null) {
// delivered_at表示已提交到至少一个本地连接,不等价于用户已阅读。
// UNREAD_COUNT_CHANGED没有独立消息ID,只负责同步状态,因此不写送达时间。
recipientMapper.markDelivered(deliveredUsers, push.getMessageId(), new Date());
}
}
}
......@@ -10,19 +10,32 @@ import com.platform.business.model.vo.AttendanceSummaryVO;
import java.util.Date;
import java.util.List;
/** 出勤管理业务接口,覆盖教师开课、学员签到、教师点名和管理员统计。 */
public interface AttendanceService {
/**
* 教师开始指定课程并取得唯一验证码。
* 仅允许在计划开始时间到课程结束时间之间调用,重复调用返回同一会话。
*/
AttendanceSessionVO startClass(Integer subjectId, String teacherId);
/**
* 学员签到。计划开始后的验证码窗口内校验IP和验证码,窗口结束后只校验IP并记为迟到。
*/
AttendanceRecordVO checkIn(AttendanceCheckInDTO request, String studentId, String clientIp);
/** 教师将本人课程中的学员手动标记为正常、迟到或缺勤。 */
AttendanceRecordVO updateStatus(AttendanceStatusUpdateDTO request, String teacherId);
/** 查询本人授课课程的完整学员点名册。 */
List<AttendanceRecordVO> teacherRoster(Integer subjectId, String teacherId);
/** 按条件查询出勤记录。 */
List<AttendanceRecordVO> queryRecords(AttendanceQueryDTO query);
/** 查询总览、按学员和按课程三个维度的出勤统计。 */
AttendanceSummaryVO querySummary(AttendanceQueryDTO query);
/** 将日期范围内已经结束且尚无出勤记录的学员补记为缺勤。 */
void finalizeEndedSubjects(Date startDate, Date endDate);
}
package com.platform.business.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.platform.business.model.entity.SysPhoneRoleEntity;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.utils.JwtTokenUtil;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 消息中心使用的登录用户解析服务。
*
* <p>所有用户侧接口都忽略客户端提交的userId,统一从JWT中的手机号查询真实用户记录;
* 管理发布接口还会额外查询角色映射,避免普通用户伪造管理端请求。</p>
*/
@Service
public class AuthenticatedUserService {
@Resource
private JwtTokenUtil jwtTokenUtil;
@Resource
private UserService userService;
@Resource
private SysPhoneRoleService phoneRoleService;
public UserEntity current(HttpServletRequest request) {
// 兼容“Bearer token”和直接token两种项目现有调用形式。
String token = request.getHeader("Authorization");
if (token == null || token.trim().isEmpty()) {
throw new BusinessException("未获取到登录凭证");
}
token = token.trim();
if (token.regionMatches(true, 0, "Bearer ", 0, 7)) {
token = token.substring(7).trim();
}
String phone;
try {
phone = jwtTokenUtil.getUsernameFromToken(token);
} catch (Exception e) {
throw new BusinessException("登录凭证无效或已过期");
}
UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>()
.eq(UserEntity::getPhoneNumber, phone), false);
if (user == null) {
throw new BusinessException("当前登录用户不存在");
}
return user;
}
public void requireAdmin(UserEntity user) {
// 项目当前使用中文角色名和手机号映射,因此沿用既有权限数据结构。
List<SysPhoneRoleEntity> roles = phoneRoleService.queryByPhone(user.getPhoneNumber());
boolean admin = roles != null && roles.stream().anyMatch(role -> "管理员".equals(role.getRoleName()));
if (!admin) {
throw new BusinessException("只有管理员可以发布平台消息");
}
}
}
package com.platform.business.service;
import com.platform.business.model.dto.NotificationPublishDTO;
/**
* Business服务内部统一消息发布接口。
*
* <p>考试发布、考试即将开始、成绩发布、请假审批、课程调整等业务类只需要注入本接口,
* 不需要依赖消息列表、已读或删除等消息中心管理能力。接口实现仍然使用事务发件箱,
* 因此建议在业务操作的数据库事务中调用:业务事务回滚时,待发布消息也会一起回滚。</p>
*
* <p>本接口仅作为{@code practical-business}进程内的Spring Bean使用,不对应HTTP、Feign或其他
* 远程调用入口。普通前端用户无法通过该接口自行构造和发送消息。</p>
*/
public interface BusinessNotificationPublisher {
/**
* 发布一条业务消息。
*
* <p>方法只在当前事务中写入{@code notification_outbox},不会同步等待消息落库或WebSocket发送。
* 后台发布任务会通过RabbitMQ可靠投递,消息消费者完成接收人落库后,再实时推送消息及未读数刷新标记。</p>
*
* @param request 消息内容、业务关联信息、接收用户/角色/班级以及可选预约时间
* @param senderId 触发业务操作的用户ID;定时任务或系统事件可以传{@code null}
* @param senderName 发送人展示名称;系统事件建议使用“系统通知”
* @return 全链路事件ID,可记录到业务日志中用于幂等重试和问题排查
*/
String publish(NotificationPublishDTO request, String senderId, String senderName);
}
......@@ -3,5 +3,6 @@ package com.platform.business.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.platform.business.model.entity.ClassSubjectAttendanceSessionEntity;
/** 课程签到会话的通用持久化服务。 */
public interface ClassSubjectAttendanceSessionService extends IService<ClassSubjectAttendanceSessionEntity> {
}
......@@ -7,20 +7,31 @@ import com.platform.business.model.vo.LeaveApplicationVO;
import java.util.List;
/** 请假管理业务接口,覆盖学员申请以及教师、管理员单级审批。 */
public interface LeaveManagementService {
/** 新增请假申请,并自动关联请假时间内重叠的全部课程。 */
LeaveApplicationVO apply(LeaveApplyDTO request, String studentId);
/** 修改本人仍处于待审批状态的申请,并重新计算关联课程和附件。 */
LeaveApplicationVO update(LeaveApplyDTO request, String studentId);
/** 撤回本人仍处于待审批状态的申请。 */
boolean withdraw(String leaveId, String studentId);
/**
* 审批请假申请。教师和管理员共用单级审批流程,先成功更新PENDING状态者生效。
*/
LeaveApplicationVO review(String leaveId, LeaveReviewDTO request, String approverId, String approverRole);
/** 按学员端、教师端或管理端限定条件查询申请列表。 */
List<LeaveApplicationVO> queryApplications(LeaveQueryDTO query);
/** 查询本人请假详情并校验申请归属。 */
LeaveApplicationVO studentDetail(String leaveId, String studentId);
/** 查询与教师本人授课课程相关的请假详情。 */
LeaveApplicationVO teacherDetail(String leaveId, String teacherId);
/** 管理员查询任意请假详情。 */
LeaveApplicationVO adminDetail(String leaveId);
}
package com.platform.business.service;
import com.platform.business.model.dto.NotificationEventDTO;
import java.util.List;
/** 将发布事件中的用户、角色、班级和全员范围解析成去重后的用户ID。 */
public interface NotificationAudienceService {
/**
* 解析接收人并取各范围的并集。
*
* @return 保持首次出现顺序的去重用户ID集合
*/
List<String> resolve(NotificationEventDTO event);
}
package com.platform.business.service;
import com.platform.business.model.dto.NotificationEventDTO;
import com.platform.business.model.dto.NotificationMessageQueryDTO;
import com.platform.business.model.vo.NotificationMessageVO;
import java.util.List;
/**
* 消息中心完整应用服务,供三端HTTP接口和RabbitMQ消费者使用。
*
* <p>该接口继承{@link BusinessNotificationPublisher},管理员发布接口继续通过本服务调用原有发布方法;
* 考试、请假等普通业务类建议只注入更小的{@code BusinessNotificationPublisher}接口,避免依赖无关能力。</p>
*/
public interface NotificationMessageService extends BusinessNotificationPublisher {
/** 消费RabbitMQ事件,幂等保存正文和接收人,并在事务提交后触发在线推送。 */
void consume(NotificationEventDTO event);
/** 按当前用户和筛选条件查询消息列表。 */
List<NotificationMessageVO> query(NotificationMessageQueryDTO query);
/** 校验消息归属、读取详情,并原子更新当前用户的已读状态。 */
NotificationMessageVO detailAndMarkRead(String messageId, String userId);
/** 标记当前用户的一条消息为已读。 */
boolean markRead(String messageId, String userId);
/** 标记当前用户所有未删除消息为已读,返回实际更新数量。 */
int markAllRead(String userId);
/** 仅逻辑删除当前用户视图中的消息,不影响其他接收人。 */
boolean delete(String messageId, String userId);
/** 逻辑删除当前用户的全部已读消息。 */
int clearRead(String userId);
/** 获取当前用户有效未读数;Redis不可用时自动回源MySQL。 */
long unreadCount(String userId);
}
package com.platform.business.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.util.UUID;
/**
* 当前推送实例的路由标识。
*
* <p>该值同时用于Redis在线目录字段和RabbitMQ节点队列routing key。生产环境可以显式配置;
* 未配置时由应用名、主机名和随机后缀组合,避免同一主机启动多个实例时发生队列冲突。</p>
*/
@Component
public class NotificationNodeIdentity {
private final String nodeId;
/** 创建并清洗节点ID,确保只包含RabbitMQ队列名安全字符。 */
public NotificationNodeIdentity(@Value("${notification.node-id:}") String configuredNodeId,
@Value("${spring.application.name:practical-business}") String applicationName) {
this.nodeId = hasText(configuredNodeId) ? sanitize(configuredNodeId)
: sanitize(applicationName + "-" + hostName() + "-" + UUID.randomUUID().toString().substring(0, 8));
}
public String getNodeId() {
return nodeId;
}
private String hostName() {
// 容器或受限环境无法解析主机名时使用local,不阻止应用启动。
try {
return InetAddress.getLocalHost().getHostName();
} catch (Exception ignored) {
return "local";
}
}
private String sanitize(String value) {
return value.replaceAll("[^a-zA-Z0-9_.-]", "-");
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
}
package com.platform.business.service;
import com.platform.business.constant.NotificationConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis在线目录。
*
* <p>WebSocket Session不能序列化,仍保存在节点本地;Redis Hash只保存
* {@code nodeId:connectionId -> 最后心跳时间},供消息消费者查找用户位于哪些服务节点。</p>
*/
@Service
@Slf4j
public class NotificationPresenceService {
@Resource
private StringRedisTemplate redisTemplate;
@Resource
private NotificationNodeIdentity nodeIdentity;
/** 在线目录有效期应大于心跳周期,默认允许连续丢失三次心跳。 */
@Value("${notification.websocket.presence-ttl-seconds:120}")
private long presenceTtlSeconds;
/** 新连接注册与心跳刷新使用相同数据结构。 */
public void register(String userId, String connectionId) {
refresh(userId, connectionId);
}
/** 更新连接最后活跃时间,并刷新整个用户Hash的过期时间。 */
public void refresh(String userId, String connectionId) {
String key = key(userId);
try {
redisTemplate.opsForHash().put(key, field(connectionId), String.valueOf(System.currentTimeMillis()));
redisTemplate.expire(key, presenceTtlSeconds, TimeUnit.SECONDS);
} catch (Exception e) {
log.warn("更新 WebSocket 在线目录失败,将保持本机推送: {}", e.getMessage());
}
}
/** 连接正常关闭时主动移除字段;异常宕机产生的残留字段由TTL和时间戳过滤。 */
public void unregister(String userId, String connectionId) {
try {
redisTemplate.opsForHash().delete(key(userId), field(connectionId));
} catch (Exception e) {
log.warn("移除 WebSocket 在线目录失败: {}", e.getMessage());
}
}
/**
* 查询用户当前所在节点集合。
* 读取时会顺便清理超过presenceTtlSeconds的连接字段,防止活跃用户Hash中长期残留旧标签页。
*/
public Set<String> findNodeIds(String userId) {
try {
Map<Object, Object> entries = redisTemplate.opsForHash().entries(key(userId));
if (entries.isEmpty()) {
return Collections.emptySet();
}
long validAfter = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(presenceTtlSeconds);
Set<String> nodes = new HashSet<>();
for (Map.Entry<Object, Object> entry : entries.entrySet()) {
String value = String.valueOf(entry.getValue());
String field = String.valueOf(entry.getKey());
try {
if (Long.parseLong(value) >= validAfter) {
// field格式固定为nodeId:connectionId,只返回节点部分用于RabbitMQ路由。
int separator = field.indexOf(':');
if (separator > 0) {
nodes.add(field.substring(0, separator));
}
} else {
redisTemplate.opsForHash().delete(key(userId), field);
}
} catch (NumberFormatException ignored) {
redisTemplate.opsForHash().delete(key(userId), field);
}
}
return nodes;
} catch (Exception e) {
log.warn("查询 WebSocket 在线目录失败,将使用本机状态: {}", e.getMessage());
return Collections.emptySet();
}
}
private String key(String userId) {
return NotificationConstants.PRESENCE_KEY_PREFIX + userId;
}
private String field(String connectionId) {
return nodeIdentity.getNodeId() + ":" + connectionId;
}
}
package com.platform.business.service;
import com.platform.business.model.dto.NotificationPushDTO;
import java.util.List;
/** 在线消息节点路由抽象;持久化服务不需要感知具体WebSocket实例。 */
public interface NotificationPushDispatcher {
/** 根据Redis在线目录将用户按节点分组,并发送节点级RabbitMQ推送。 */
void dispatch(List<String> userIds, NotificationPushDTO push);
}
package com.platform.business.service;
import com.platform.business.constant.NotificationConstants;
import com.platform.business.model.vo.NotificationSocketTicketVO;
import com.platform.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* 一次性WebSocket票据服务。
*
* <p>用户先通过正常JWT接口申请随机票据,再将短票据放入WebSocket URL。票据默认60秒过期,
* 并通过Lua脚本原子执行GET+DEL,保证两个并发握手不能重复使用同一票据。</p>
*/
@Service
@Slf4j
public class NotificationSocketTicketService {
/** 原子读取并删除票据,不能拆成两个Redis命令,否则存在并发复用窗口。 */
private static final DefaultRedisScript<String> CONSUME_SCRIPT = new DefaultRedisScript<>(
"local value = redis.call('GET', KEYS[1]); " +
"if value then redis.call('DEL', KEYS[1]); end; return value;", String.class);
@Resource
private StringRedisTemplate redisTemplate;
@Value("${notification.websocket.ticket-ttl-seconds:60}")
private long ticketTtlSeconds;
/** 为已通过JWT认证的用户创建随机票据及其连接路径。 */
public NotificationSocketTicketVO issue(String userId) {
String ticket = UUID.randomUUID().toString().replace("-", "");
try {
redisTemplate.opsForValue().set(key(ticket), userId, ticketTtlSeconds, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("创建 WebSocket 票据失败", e);
throw new BusinessException("实时消息服务暂不可用,请稍后重试");
}
return new NotificationSocketTicketVO(ticket,
"/notification/websocket/" + userId, ticketTtlSeconds);
}
/**
* 消费并删除票据。
*
* @return 票据对应用户ID;无效、过期、已使用或Redis异常时返回null
*/
public String consume(String ticket) {
if (ticket == null || ticket.trim().isEmpty()) {
return null;
}
try {
return redisTemplate.execute(CONSUME_SCRIPT, Collections.singletonList(key(ticket.trim())));
} catch (Exception e) {
log.error("消费 WebSocket 票据失败", e);
return null;
}
}
private String key(String ticket) {
return NotificationConstants.TICKET_KEY_PREFIX + ticket;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment