Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
邬吉朋
practical_train
Commits
0b2419f1
Commit
0b2419f1
authored
Aug 10, 2026
by
王蔡翾
Browse files
消息中心,消息队列和websocket,以及请假注释
parent
1ea1a030
Changes
86
Show whitespace changes
Inline
Side-by-side
practical-business/src/main/resources/com/platform/business/mapper/StudentLeaveAttachmentMapper.xml
View file @
0b2419f1
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace=
"com.platform.business.mapper.StudentLeaveAttachmentMapper"
>
<!-- 只返回仍未逻辑删除的证明材料元数据。 -->
<select
id=
"queryAttachmentsByLeaveId"
resultType=
"com.platform.business.model.vo.LeaveAttachmentVO"
>
select
la.file_id as fileId,
...
...
practical-business/src/main/resources/com/platform/business/mapper/StudentLeaveSubjectMapper.xml
View file @
0b2419f1
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace=
"com.platform.business.mapper.StudentLeaveSubjectMapper"
>
<!-- 返回自动匹配课程及班级、教师信息,教师手机号完整展示。 -->
<select
id=
"querySubjectsByLeaveId"
resultType=
"com.platform.business.model.vo.LeaveSubjectVO"
>
select
s.id as subjectId,
...
...
practical-business/src/main/resources/message-center-api.md
0 → 100644
View file @
0b2419f1
# 三端消息中心接入说明
## 部署前置
1.
执行
`sql/message_center.sql`
。
2.
使用 RabbitMQ 3.8 或更高版本;持久化事件队列和死信队列使用 quorum queue。
3.
配置 Redis、RabbitMQ 环境变量。消息服务至少部署两个实例时,不要复用
`NOTIFICATION_NODE_ID`
。
4.
网关需将
`/notification/websocket/**`
按 WebSocket 协议转发至
`practical-train-business`
。
消息正文和每个用户的已读状态以 MySQL 为准。Redis 故障只影响跨节点即时定位和新票据签发;WebSocket 推送失败时,用户重新进入消息中心仍能查询到消息。
## 前端连接顺序
1.
使用登录 JWT 调用
`POST /message/socket-ticket`
。
2.
根据响应的
`endpoint`
建立
`wss://网关地址{endpoint}?ticket={ticket}`
。票据 60 秒有效且只能使用一次。
3.
收到
`NOTIFICATION`
后显示右上角弹窗;当
`refreshUnreadCount=true`
时,立即调用
`GET /message/unread/count`
刷新角标。
4.
收到
`UNREAD_COUNT_CHANGED`
时不显示弹窗,重新查询未读数;如果消息中心页面已打开,同时刷新当前列表。
5.
弹窗只使用轻量报文;点击后调用
`GET /message/{messageId}`
获取正文,该接口同时标记已读。
6.
断线后重新申请票据,并重新查询未读列表完成离线补偿。前端按
`messageId`
去重。
数量变化事件在数据库事务提交、Redis旧缓存清除之后才发送。因此客户端收到事件后查询到的是已经提交的权威数量,不能在本地通过
`+1/-1`
维护角标。短时间内连续收到多个刷新事件时,可以在100毫秒左右进行防抖,只执行一次未读数查询。
### WebSocket事件示例
新消息事件同时负责弹窗和未读数刷新:
```
json
{
"eventType"
:
"NOTIFICATION"
,
"messageId"
:
"消息ID"
,
"messageType"
:
"EXAM"
,
"title"
:
"考试即将开始"
,
"summary"
:
"请提前进入考场"
,
"refreshUnreadCount"
:
true
,
"changeType"
:
"NEW_MESSAGE"
}
```
已读、全部已读、删除或清空操作会向同一账号的全部在线标签页和设备发送状态事件:
```
json
{
"eventType"
:
"UNREAD_COUNT_CHANGED"
,
"refreshUnreadCount"
:
true
,
"changeType"
:
"MARK_READ"
}
```
## 三端通用接口
-
`POST /message/page`
:分页列表,支持
`readStatus`
、
`messageType`
、
`keyword`
。
-
`GET /message/{messageId}`
:详情并标记已读。
-
`PUT /message/{messageId}/read`
:单条已读。
-
`PUT /message/read-all`
:全部已读。
-
`GET /message/unread/count`
:未读数。
-
`DELETE /message/{messageId}`
:仅删除当前用户视图。
-
`DELETE /message/read`
:清空当前用户已读消息。
-
`POST /message/admin/publish`
:管理员发布或预约发布消息。
管理员发布请求可组合
`recipientUserIds`
、
`recipientRoleNames`
、
`recipientClassIds`
和
`broadcast`
。预约时间由
`scheduledAt`
指定。
## 业务模块接入
考试发布、考试即将开始、成绩发布、请假审批、课程变更等业务类只需要注入
`BusinessNotificationPublisher`
。该接口仅存在于
`practical-business`
服务内部,不提供HTTP或Feign入口。
建议在业务数据库事务中调用:
```
java
@Resource
private
BusinessNotificationPublisher
notificationPublisher
;
// 与考试发布、请假审批等业务数据处于同一个数据库事务。
notificationPublisher
.
publish
(
command
,
operatorId
,
operatorName
);
```
该调用只写
`notification_outbox`
,不直接访问 RabbitMQ,因此业务提交与通知事件不会发生数据库/MQ双写不一致。后台任务抢占发件箱记录,使用 Publisher Confirm 发布;消费失败进入 30 秒 TTL 重试队列,累计失败后进入死信队列。
系统定时提醒没有人工操作人时,
`senderId`
可以传
`null`
,
`senderName`
使用“系统通知”。原有
`POST /message/admin/publish`
管理员手动发布接口保持不变,并继续执行管理员角色校验。
## RabbitMQ 拓扑
-
`notification.events.x`
:Topic Exchange,按
`notification.system`
、
`notification.exam`
等路由。
-
`notification.persist.q`
:quorum queue,落库消费者。
-
`notification.retry.30s.q`
:TTL 重试队列,过期后通过 DLX 返回事件交换机。
-
`notification.dead.q`
:超过重试次数的死信事件。
-
`notification.push.x`
:Direct Exchange,routing key 为节点 ID;每个服务节点仅有一个临时推送队列,不会按用户创建队列。
practical-business/src/main/resources/sql/message_center.sql
0 → 100644
View file @
0b2419f1
-- 三端消息中心(MySQL 5.7+/8.0)
-- RabbitMQ 只负责可靠事件和在线推送,以下表是消息及离线状态的最终数据源。
create
table
if
not
exists
notification_message
(
id
varchar
(
32
)
not
null
comment
'消息ID'
,
event_id
varchar
(
64
)
not
null
comment
'全链路幂等事件ID'
,
message_type
varchar
(
32
)
not
null
comment
'SYSTEM/EXAM/SCORE/LEAVE/COURSE/TEACHING_PLAN'
,
title
varchar
(
200
)
not
null
,
summary
varchar
(
500
)
null
,
content
text
not
null
,
sender_id
varchar
(
64
)
null
,
sender_name
varchar
(
100
)
null
,
business_type
varchar
(
64
)
null
,
business_id
varchar
(
64
)
null
,
action_url
varchar
(
500
)
null
,
priority
varchar
(
16
)
not
null
default
'NORMAL'
comment
'NORMAL/IMPORTANT/URGENT'
,
created_at
datetime
(
3
)
not
null
,
expires_at
datetime
(
3
)
null
,
primary
key
(
id
),
unique
key
uk_notification_message_event
(
event_id
),
key
idx_notification_message_created
(
created_at
),
key
idx_notification_message_business
(
business_type
,
business_id
)
)
engine
=
InnoDB
default
charset
=
utf8mb4
collate
=
utf8mb4_unicode_ci
comment
=
'消息正文'
;
create
table
if
not
exists
notification_message_recipient
(
id
varchar
(
32
)
not
null
,
message_id
varchar
(
32
)
not
null
,
user_id
varchar
(
64
)
not
null
,
read_flag
tinyint
(
1
)
not
null
default
0
,
read_at
datetime
(
3
)
null
,
deleted_flag
tinyint
(
1
)
not
null
default
0
,
deleted_at
datetime
(
3
)
null
,
delivered_at
datetime
(
3
)
null
comment
'已投递到至少一个在线连接的时间'
,
created_at
datetime
(
3
)
not
null
,
primary
key
(
id
),
unique
key
uk_notification_recipient
(
message_id
,
user_id
),
key
idx_notification_recipient_inbox
(
user_id
,
deleted_flag
,
read_flag
,
created_at
),
constraint
fk_notification_recipient_message
foreign
key
(
message_id
)
references
notification_message
(
id
)
)
engine
=
InnoDB
default
charset
=
utf8mb4
collate
=
utf8mb4_unicode_ci
comment
=
'用户消息状态'
;
create
table
if
not
exists
notification_outbox
(
id
varchar
(
32
)
not
null
,
event_id
varchar
(
64
)
not
null
,
routing_key
varchar
(
100
)
not
null
,
payload
longtext
not
null
,
status
varchar
(
16
)
not
null
comment
'NEW/PUBLISHING/PUBLISHED/RETRY/FAILED'
,
retry_count
int
not
null
default
0
,
scheduled_at
datetime
(
3
)
not
null
,
next_retry_at
datetime
(
3
)
null
,
published_at
datetime
(
3
)
null
,
last_error
varchar
(
1000
)
null
,
created_at
datetime
(
3
)
not
null
,
updated_at
datetime
(
3
)
not
null
,
primary
key
(
id
),
unique
key
uk_notification_outbox_event
(
event_id
),
key
idx_notification_outbox_due
(
status
,
scheduled_at
,
next_retry_at
)
)
engine
=
InnoDB
default
charset
=
utf8mb4
collate
=
utf8mb4_unicode_ci
comment
=
'消息事务发件箱'
;
practical-business/src/test/java/com/platform/business/service/impl/NotificationMessageServiceImplTest.java
0 → 100644
View file @
0b2419f1
package
com.platform.business.service.impl
;
import
com.alibaba.fastjson2.JSON
;
import
com.platform.business.mapper.NotificationMessageMapper
;
import
com.platform.business.mapper.NotificationMessageRecipientMapper
;
import
com.platform.business.mapper.NotificationOutboxMapper
;
import
com.platform.business.model.dto.NotificationEventDTO
;
import
com.platform.business.model.dto.NotificationPublishDTO
;
import
com.platform.business.model.dto.NotificationPushDTO
;
import
com.platform.business.model.entity.NotificationMessageEntity
;
import
com.platform.business.model.entity.NotificationOutboxEntity
;
import
com.platform.business.service.BusinessNotificationPublisher
;
import
com.platform.business.service.NotificationAudienceService
;
import
com.platform.business.service.NotificationPushDispatcher
;
import
com.platform.business.service.NotificationUnreadCache
;
import
com.platform.exception.BusinessException
;
import
org.junit.jupiter.api.Test
;
import
org.junit.jupiter.api.extension.ExtendWith
;
import
org.mockito.ArgumentCaptor
;
import
org.mockito.InjectMocks
;
import
org.mockito.Mock
;
import
org.mockito.junit.jupiter.MockitoExtension
;
import
org.springframework.transaction.support.TransactionSynchronization
;
import
org.springframework.transaction.support.TransactionSynchronizationManager
;
import
java.util.Arrays
;
import
java.util.Collections
;
import
java.util.Date
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertEquals
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertNotNull
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertTrue
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertThrows
;
import
static
org
.
mockito
.
ArgumentMatchers
.
any
;
import
static
org
.
mockito
.
ArgumentMatchers
.
anyList
;
import
static
org
.
mockito
.
ArgumentMatchers
.
eq
;
import
static
org
.
mockito
.
Mockito
.
times
;
import
static
org
.
mockito
.
Mockito
.
verify
;
import
static
org
.
mockito
.
Mockito
.
verifyNoInteractions
;
import
static
org
.
mockito
.
Mockito
.
when
;
/** 消息中心核心服务单元测试,不依赖真实MySQL、RabbitMQ或Redis。 */
@ExtendWith
(
MockitoExtension
.
class
)
class
NotificationMessageServiceImplTest
{
@Mock
private
NotificationMessageMapper
messageMapper
;
@Mock
private
NotificationMessageRecipientMapper
recipientMapper
;
@Mock
private
NotificationOutboxMapper
outboxMapper
;
@Mock
private
NotificationAudienceService
audienceService
;
@Mock
private
NotificationPushDispatcher
pushDispatcher
;
@Mock
private
NotificationUnreadCache
unreadCache
;
@InjectMocks
private
NotificationMessageServiceImpl
service
;
/** 验证发布请求只写入包含完整事件快照的事务发件箱。 */
@Test
void
publishWritesCompleteTransactionalOutboxEvent
()
{
NotificationPublishDTO
request
=
new
NotificationPublishDTO
();
request
.
setMessageType
(
"EXAM"
);
request
.
setTitle
(
"考试即将开始"
);
request
.
setContent
(
"请提前十分钟进入考场"
);
request
.
setRecipientUserIds
(
Collections
.
singletonList
(
"user-1"
));
// 业务模块仅依赖单方法发布接口,不需要感知消息中心的查询和状态管理能力。
BusinessNotificationPublisher
publisher
=
service
;
String
eventId
=
publisher
.
publish
(
request
,
"admin-1"
,
"管理员"
);
ArgumentCaptor
<
NotificationOutboxEntity
>
captor
=
ArgumentCaptor
.
forClass
(
NotificationOutboxEntity
.
class
);
verify
(
outboxMapper
).
insert
(
captor
.
capture
());
NotificationOutboxEntity
outbox
=
captor
.
getValue
();
NotificationEventDTO
event
=
JSON
.
parseObject
(
outbox
.
getPayload
(),
NotificationEventDTO
.
class
);
assertEquals
(
eventId
,
outbox
.
getEventId
());
assertEquals
(
"notification.exam"
,
outbox
.
getRoutingKey
());
assertEquals
(
"EXAM"
,
event
.
getMessageType
());
assertEquals
(
"admin-1"
,
event
.
getSenderId
());
assertNotNull
(
outbox
.
getScheduledAt
());
}
/** 验证没有任何接收范围的消息在写库前被拒绝。 */
@Test
void
publishRejectsRequestWithoutAudience
()
{
NotificationPublishDTO
request
=
new
NotificationPublishDTO
();
request
.
setMessageType
(
"SYSTEM"
);
request
.
setTitle
(
"系统通知"
);
request
.
setContent
(
"内容"
);
assertThrows
(
BusinessException
.
class
,
()
->
service
.
publish
(
request
,
"admin-1"
,
"管理员"
));
}
/** 验证消费者先持久化接收人,再构造在线推送并使未读缓存失效。 */
@Test
void
consumePersistsRecipientsAndDispatchesAfterPersistence
()
{
NotificationEventDTO
event
=
new
NotificationEventDTO
();
event
.
setEventId
(
"event-1"
);
event
.
setMessageType
(
"LEAVE"
);
event
.
setTitle
(
"请假审批完成"
);
event
.
setContent
(
"审批结果:通过"
);
event
.
setCreatedAt
(
new
Date
());
NotificationMessageEntity
persisted
=
new
NotificationMessageEntity
();
persisted
.
setId
(
"message-1"
);
persisted
.
setEventId
(
"event-1"
);
persisted
.
setMessageType
(
"LEAVE"
);
persisted
.
setTitle
(
event
.
getTitle
());
persisted
.
setContent
(
event
.
getContent
());
persisted
.
setPriority
(
"NORMAL"
);
persisted
.
setCreatedAt
(
event
.
getCreatedAt
());
when
(
messageMapper
.
selectByEventId
(
"event-1"
)).
thenReturn
(
persisted
);
when
(
audienceService
.
resolve
(
event
)).
thenReturn
(
Arrays
.
asList
(
"user-1"
,
"user-2"
));
service
.
consume
(
event
);
verify
(
messageMapper
).
insertIgnore
(
any
(
NotificationMessageEntity
.
class
));
verify
(
recipientMapper
).
insertBatchIgnore
(
anyList
());
verify
(
unreadCache
,
times
(
2
)).
evict
(
any
());
ArgumentCaptor
<
NotificationPushDTO
>
pushCaptor
=
ArgumentCaptor
.
forClass
(
NotificationPushDTO
.
class
);
verify
(
pushDispatcher
).
dispatch
(
eq
(
Arrays
.
asList
(
"user-1"
,
"user-2"
)),
pushCaptor
.
capture
());
assertEquals
(
"NOTIFICATION"
,
pushCaptor
.
getValue
().
getEventType
());
assertEquals
(
"NEW_MESSAGE"
,
pushCaptor
.
getValue
().
getChangeType
());
assertTrue
(
pushCaptor
.
getValue
().
getRefreshUnreadCount
());
}
/** 验证标记已读后会通知同一用户的全部连接重新查询未读数。 */
@Test
void
markReadDispatchesUnreadCountChangedEvent
()
{
when
(
recipientMapper
.
markRead
(
eq
(
"message-1"
),
eq
(
"user-1"
),
any
(
Date
.
class
))).
thenReturn
(
1
);
boolean
changed
=
service
.
markRead
(
"message-1"
,
"user-1"
);
assertTrue
(
changed
);
verify
(
unreadCache
).
evict
(
"user-1"
);
ArgumentCaptor
<
NotificationPushDTO
>
pushCaptor
=
ArgumentCaptor
.
forClass
(
NotificationPushDTO
.
class
);
verify
(
pushDispatcher
).
dispatch
(
eq
(
Collections
.
singletonList
(
"user-1"
)),
pushCaptor
.
capture
());
assertEquals
(
"UNREAD_COUNT_CHANGED"
,
pushCaptor
.
getValue
().
getEventType
());
assertEquals
(
"MARK_READ"
,
pushCaptor
.
getValue
().
getChangeType
());
assertTrue
(
pushCaptor
.
getValue
().
getRefreshUnreadCount
());
}
/** 已经是已读状态时数据库更新数为0,不重复广播无意义的数量变化事件。 */
@Test
void
markReadDoesNotDispatchWhenStateDidNotChange
()
{
when
(
recipientMapper
.
markRead
(
eq
(
"message-1"
),
eq
(
"user-1"
),
any
(
Date
.
class
))).
thenReturn
(
0
);
boolean
changed
=
service
.
markRead
(
"message-1"
,
"user-1"
);
assertEquals
(
false
,
changed
);
verify
(
pushDispatcher
,
times
(
0
)).
dispatch
(
anyList
(),
any
());
}
/** 验证缓存失效和数量事件严格延迟到事务提交之后,防止客户端查询到旧数量。 */
@Test
void
unreadCountSynchronizationRunsOnlyAfterTransactionCommit
()
{
when
(
recipientMapper
.
markRead
(
eq
(
"message-1"
),
eq
(
"user-1"
),
any
(
Date
.
class
))).
thenReturn
(
1
);
TransactionSynchronizationManager
.
setActualTransactionActive
(
true
);
TransactionSynchronizationManager
.
initSynchronization
();
try
{
service
.
markRead
(
"message-1"
,
"user-1"
);
verifyNoInteractions
(
unreadCache
,
pushDispatcher
);
for
(
TransactionSynchronization
synchronization
:
TransactionSynchronizationManager
.
getSynchronizations
())
{
synchronization
.
afterCommit
();
}
verify
(
unreadCache
).
evict
(
"user-1"
);
verify
(
pushDispatcher
).
dispatch
(
eq
(
Collections
.
singletonList
(
"user-1"
)),
any
(
NotificationPushDTO
.
class
));
}
finally
{
TransactionSynchronizationManager
.
clearSynchronization
();
TransactionSynchronizationManager
.
setActualTransactionActive
(
false
);
}
}
}
practical-gateway/src/main/java/com/platform/gateway/filter/IgnoreUrlsRemoveJwtFilter.java
View file @
0b2419f1
...
...
@@ -52,6 +52,12 @@ public class IgnoreUrlsRemoveJwtFilter implements WebFilter {
ServerHttpResponse
response
=
exchange
.
getResponse
();
URI
uri
=
request
.
getURI
();
PathMatcher
pathMatcher
=
new
AntPathMatcher
();
// 浏览器原生 WebSocket 无法设置 Authorization 请求头。消息长连接使用业务服务签发的
// 60 秒一次性 ticket 完成身份校验,因此这里只放行握手,不代表匿名访问消息数据接口。
if
(
pathMatcher
.
match
(
"/**/notification/websocket/**"
,
uri
.
getPath
())
||
pathMatcher
.
match
(
"/notification/websocket/**"
,
uri
.
getPath
()))
{
return
chain
.
filter
(
exchange
);
}
//1.判断是否是白名单的url,如果是则移除JWT请求头,并通过过
List
<
String
>
ignoreUrls
=
ignoreUrlsConfig
.
getUrls
();
if
(
CollUtil
.
isNotEmpty
(
ignoreUrls
))
{
...
...
Prev
1
2
3
4
5
Next
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment