功能:支持按通道ID定向发送

This commit is contained in:
xiaowang
2026-03-23 11:38:42 +08:00
parent 997c13c454
commit fb43aae384
11 changed files with 177 additions and 57 deletions
@@ -1,15 +1,14 @@
package com.xiaowang.messagehub.dto;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Map;
/**
* 消息队列中推送消息实体类
* 用于封装消息推送所需的所有信息,包括接收者、渠道类型、消息类型等
* Message payload for queue dispatch.
*
* @author xiaowang
* @date 2023-03-21
@@ -17,34 +16,34 @@ import java.util.Map;
@Data
public class MessageDTO {
// 接收者,不能为空
@NotBlank(message = "接收者不能为空")
@NotBlank(message = "接收目标不能为空")
private String receiver;
// 渠道类型,只能是EMAIL、SMS、PUSH或WECHAT中的一种且不能为空
@NotBlank(message = "渠道类型不能为空")
@Pattern(regexp = "^(EMAIL|SMS|PUSH|WECHAT)$", message = "渠道类型必须是EMAIL、SMS、PUSH或WECHAT")
@NotBlank(message = "通道类型不能为空")
@Pattern(regexp = "^(EMAIL|SMS|PUSH|WECHAT)$", message = "通道类型必须是 EMAIL、SMS、PUSH 或 WECHAT")
private String channelType;
// 消息类型,只能是NOTIFICATION、VERIFICATION、PROMOTION或ALERT中的一种且不能为空
@NotBlank(message = "消息类型不能为空")
@Pattern(regexp = "^(NOTIFICATION|VERIFICATION|PROMOTION|ALERT)$", message = "消息类型必须是NOTIFICATION、VERIFICATION、PROMOTION或ALERT")
@Pattern(regexp = "^(NOTIFICATION|VERIFICATION|PROMOTION|ALERT)$", message = "消息类型必须是 NOTIFICATION、VERIFICATION、PROMOTION 或 ALERT")
private String msgType;
// 模板编码,用于标识使用的消息模板,长度不能超过50
@Size(max = 50, message = "模板编码长度不能超过50")
@Size(max = 50, message = "模板编码长度不能超过 50")
private String templateCode;
// 模板参数,用于填充模板中的变量,使用Map存储键值对
private Map<String, Object> templateParams;
// 来源系统标识,表示消息发送的系统,长度不能超过50且不能为空
/**
* Optional dispatch target.
* When null, MessageHub uses the current default channel of the given type.
* When provided, MessageHub matches by channelType + channelId.
*/
private Long channelId;
@NotBlank(message = "来源系统不能为空")
@Size(max = 50, message = "来源系统长度不能超过50")
@Size(max = 50, message = "来源系统长度不能超过 50")
private String sourceSystem;
// 消息的唯一标识,用于追踪和去重,长度不能超过100且不能为空
@NotBlank(message = "唯一标识不能为空")
@Size(max = 100, message = "唯一标识长度不能超过100")
@Size(max = 100, message = "唯一标识长度不能超过 100")
private String uniqueId;
}
@@ -62,7 +62,7 @@ public class EmailQueueListener {
String content = buildContent(messageDTO);
// 发送邮件
emailSendService.sendEmail(messageDTO.getReceiver(), subject, content);
emailSendService.sendEmail(messageDTO.getReceiver(), subject, content, messageDTO.getChannelId());
// 打印处理完成的日志
log.info("========================================");
@@ -133,4 +133,4 @@ public class EmailQueueListener {
}
}
}
}
}
@@ -16,5 +16,7 @@ public class SmsDispatchRequest {
private String content;
private Long channelId;
private Map<String, Object> templateParams = new LinkedHashMap<>();
}
@@ -15,7 +15,11 @@ public class EmailSendService {
}
public void sendEmail(String to, String subject, String content) {
log.info("准备通过数据库配置的邮件通道发送消息,收件人: {}, 主题: {}", to, subject);
messageChannelService.sendEmail(to, subject, content);
sendEmail(to, subject, content, null);
}
public void sendEmail(String to, String subject, String content, Long channelId) {
log.info("Preparing email dispatch, receiver: {}, subject: {}, channelId: {}", to, subject, channelId);
messageChannelService.sendEmail(to, subject, content, channelId);
}
}
@@ -168,12 +168,16 @@ public class MessageChannelService {
}
public void sendEmail(String to, String subject, String content) {
ManagedChannelConfig channelConfig = selectActiveChannel(ChannelTypeEnum.EMAIL);
sendEmail(to, subject, content, null);
}
public void sendEmail(String to, String subject, String content, Long channelId) {
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.EMAIL, channelId);
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, to, subject, content);
}
public void sendSms(SmsDispatchRequest request) {
ManagedChannelConfig channelConfig = selectActiveChannel(ChannelTypeEnum.SMS);
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.SMS, request.getChannelId());
if (ChannelProviderCodeEnum.SPUG.getCode().equalsIgnoreCase(channelConfig.entity().getProviderCode())
&& !StringUtils.hasText(request.getTemplateExternalId())) {
request.setTemplateExternalId(requireTemplateExternalId(request.getTemplateCode()));
@@ -263,6 +267,24 @@ public class MessageChannelService {
return new ManagedChannelConfig(entity, readJsonMap(entity.getConfigJson()), readSecretJson(entity.getSecretJson()));
}
private ManagedChannelConfig resolveDispatchChannel(ChannelTypeEnum channelType, Long channelId) {
if (channelId != null) {
return selectSpecifiedChannel(channelType, channelId);
}
return selectActiveChannel(channelType);
}
private ManagedChannelConfig selectSpecifiedChannel(ChannelTypeEnum channelType, Long channelId) {
MessageChannelConfigDO entity = requireChannel(channelId);
if (!channelType.getCode().equalsIgnoreCase(entity.getChannelType())) {
throw new IllegalArgumentException("Channel type does not match channelId: " + channelId);
}
if (entity.getEnabled() == null || entity.getEnabled() != 1) {
throw new IllegalArgumentException("Channel is disabled: " + channelId);
}
return buildManagedChannel(entity);
}
private ManagedChannelConfig selectActiveChannel(ChannelTypeEnum channelType) {
List<MessageChannelConfigDO> enabledChannels = listEnabledChannelEntities(channelType.getCode());
if (enabledChannels.isEmpty()) {
@@ -35,6 +35,7 @@ public class SmsSendServiceImpl implements SmsSendService {
dispatchRequest.setReceiver(smsMessage.getReceiver());
dispatchRequest.setTemplateCode(smsMessage.getTemplateCode());
dispatchRequest.setTemplateExternalId(templateByCode.getExternalId());
dispatchRequest.setChannelId(smsMessage.getChannelId());
dispatchRequest.setTemplateParams(smsMessage.getTemplateParams());
messageChannelService.sendSms(dispatchRequest);
@@ -39,6 +39,13 @@
- 当数据库未执行补丁时,`/admin/api/channels` 会明确提示:
- `缺少消息通道配置表,请先执行 2026-03-23_message_channel_management_patch.sql`
### 6. 新增可选 channelId 指定发送
- 业务消息体新增可选字段 `channelId`
- 不传时,仍按通道类型走默认通道
- 传入时,按 `channelType + channelId` 精确匹配
- 后台页面通道列表与保存提示中会直接展示通道 ID
## 数据库 SQL
本轮数据库变更 SQL 如下:
@@ -76,6 +76,7 @@
- 设置默认通道
- 通道健康检查
- 测试发送
- 展示通道 ID,供外围系统在消息体中按需指定
当前支持的通道类型与提供商:
@@ -114,7 +115,27 @@
5. 配置短信/邮件通道
6. 通过“健康检查”和“测试发送”验证配置
## 8. 当前已知说明
## 8. 外围系统调用约定
外围系统仍然通过 MQ 向 `MessageHub` 投递业务消息,不直接调用某个提供商。
- 不传 `channelId`
- `MessageHub` 会按消息类型自动选择当前默认通道
- 传入 `channelId`
- `MessageHub` 会按 `channelType + channelId` 精确匹配通道
- 若通道不存在、类型不匹配或已停用,则直接返回错误
推荐消息体字段:
- `receiver`
- `channelType`
- `msgType`
- `templateCode`
- `templateParams`
- `sourceSystem`
- `uniqueId`
- `channelId` 可选
## 9. 当前已知说明
- 如果未执行 SQL 补丁,管理页可以打开,但通道列表接口会提示缺少 `message_channel_config` 表
- 当前管理页未接入登录鉴权,适合内网管理场景
@@ -19,37 +19,37 @@ const PROVIDERS = {
GMAIL: {
label: "Gmail SMTP",
configFields: [
{ key: "host", label: "SMTP主机", placeholder: "smtp.gmail.com", required: true, defaultValue: "smtp.gmail.com" },
{ key: "port", label: "SMTP端口", placeholder: "587", required: true, defaultValue: "587" },
{ key: "username", label: "SMTP用户名", placeholder: "your-account@gmail.com", required: true },
{ key: "fromAddress", label: "发件人地址", placeholder: "your-account@gmail.com", required: true },
{ key: "host", label: "SMTP 主机", placeholder: "smtp.gmail.com", required: true, defaultValue: "smtp.gmail.com" },
{ key: "port", label: "SMTP 端口", placeholder: "587", required: true, defaultValue: "587" },
{ key: "username", label: "SMTP 用户名", placeholder: "your-account@gmail.com", required: true },
{ key: "fromAddress", label: "发件地址", placeholder: "your-account@gmail.com", required: true },
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: true },
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: false }
],
secretFields: [
{ key: "password", label: "SMTP密码 / 授权码", required: true }
{ key: "password", label: "SMTP 密码/授权码", required: true }
]
},
QQMAIL: {
label: "QQ邮箱 SMTP",
configFields: [
{ key: "host", label: "SMTP主机", placeholder: "smtp.qq.com", required: true, defaultValue: "smtp.qq.com" },
{ key: "port", label: "SMTP端口", placeholder: "587", required: true, defaultValue: "587" },
{ key: "username", label: "SMTP用户名", placeholder: "your-account@qq.com", required: true },
{ key: "fromAddress", label: "发件人地址", placeholder: "your-account@qq.com", required: true },
{ key: "host", label: "SMTP 主机", placeholder: "smtp.qq.com", required: true, defaultValue: "smtp.qq.com" },
{ key: "port", label: "SMTP 端口", placeholder: "587", required: true, defaultValue: "587" },
{ key: "username", label: "SMTP 用户名", placeholder: "your-account@qq.com", required: true },
{ key: "fromAddress", label: "发件地址", placeholder: "your-account@qq.com", required: true },
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: true },
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: false }
],
secretFields: [
{ key: "password", label: "SMTP密码 / 授权码", required: true }
{ key: "password", label: "SMTP 密码/授权码", required: true }
]
},
MOCK_EMAIL: {
label: "开发Mock邮件",
configFields: [
{ key: "fromAddress", label: "模拟发件人", placeholder: "mock@messagehub.local", defaultValue: "mock@messagehub.local" }
{ key: "fromAddress", label: "模拟发件地址", placeholder: "mock@messagehub.local", defaultValue: "mock@messagehub.local" }
],
secretFields: []
}
@@ -95,7 +95,7 @@ function showToast(message, isError = false) {
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => {
elements.toast.hidden = true;
}, 2800);
}, 3200);
}
async function request(url, options = {}) {
@@ -106,7 +106,10 @@ async function request(url, options = {}) {
},
...options
});
const payload = await response.json().catch(() => ({ code: 1, message: "服务响应解析失败" }));
const payload = await response.json().catch(() => ({
code: 1,
message: "服务响应解析失败"
}));
if (!response.ok || payload.code !== 0) {
throw new Error(payload.message || "请求失败");
}
@@ -119,11 +122,11 @@ function providerSchema(channelType, providerCode) {
function fillProviderOptions() {
const channelType = elements.channelType.value;
const options = Object.entries(PROVIDERS[channelType]).map(([code, schema]) => {
const providerOptions = Object.entries(PROVIDERS[channelType]).map(([code, schema]) => {
const selected = code === elements.providerCode.value ? "selected" : "";
return `<option value="${code}" ${selected}>${schema.label}</option>`;
});
elements.providerCode.innerHTML = options.join("");
elements.providerCode.innerHTML = providerOptions.join("");
if (!PROVIDERS[channelType][elements.providerCode.value]) {
elements.providerCode.value = Object.keys(PROVIDERS[channelType])[0];
}
@@ -145,6 +148,7 @@ function renderDynamicFields() {
</label>
`;
}
return `
<label>
<span>${field.label}</span>
@@ -161,7 +165,9 @@ function renderDynamicFields() {
});
const secretFields = schema.secretFields.map((field) => {
const placeholder = secretMask[field.key] ? `当前值:${secretMask[field.key]};留空则保持不变` : "";
const placeholder = secretMask[field.key]
? `当前值:${secretMask[field.key]},留空则保持不变`
: "";
return `
<label>
<span>${field.label}</span>
@@ -191,7 +197,9 @@ function resetForm(channel = null) {
elements.enabled.checked = channel?.enabled ?? true;
elements.isDefault.checked = channel?.isDefault ?? false;
elements.formTitle.textContent = channel ? "编辑通道" : "新增通道";
elements.formSubtitle.textContent = channel ? "留空的敏感字段会保留原值。" : "保存后即可加入发送主链路。";
elements.formSubtitle.textContent = channel
? `当前通道 ID:${channel.id}。外围系统可在消息体中传 channelId 指定使用该通道。`
: "保存后会生成通道 ID,外围系统可在消息体中通过 channelId 指定该通道。";
renderDynamicFields();
}
@@ -223,6 +231,7 @@ function renderChannelTable() {
row.innerHTML = `
<td>
<strong>${channel.channelName}</strong>
<div class="table-note">通道 ID:${channel.id}</div>
${channel.remark ? `<div class="table-note">${channel.remark}</div>` : ""}
</td>
<td>${channel.channelType === "SMS" ? "短信" : "邮件"}</td>
@@ -253,7 +262,7 @@ function renderChannelTable() {
function fillTestChannelOptions(selectedId = "") {
const options = state.channels.map((channel) => {
const selected = String(channel.id) === String(selectedId) ? "selected" : "";
return `<option value="${channel.id}" ${selected}>${channel.channelName} / ${channel.providerName}</option>`;
return `<option value="${channel.id}" ${selected}>${channel.channelName} / ID:${channel.id} / ${channel.providerName}</option>`;
});
elements.testChannelId.innerHTML = options.join("");
if (!elements.testChannelId.value && state.channels[0]) {
@@ -289,6 +298,7 @@ async function onTableClick(event) {
if (!target) {
return;
}
const channelId = target.dataset.id;
const action = target.dataset.action;
@@ -300,19 +310,18 @@ async function onTableClick(event) {
if (action === "status") {
const channel = state.channels.find((item) => String(item.id) === String(channelId));
const payload = { enabled: !channel.enabled };
await request(`/admin/api/channels/${channelId}/status`, {
method: "POST",
body: JSON.stringify(payload)
body: JSON.stringify({ enabled: !channel.enabled })
});
showToast(channel.enabled ? "通道已停用" : "通道已启用");
showToast(channel.enabled ? `通道已停用,ID: ${channelId}` : `通道已启用,ID: ${channelId}`);
await loadChannels();
return;
}
if (action === "health") {
await request(`/admin/api/channels/${channelId}/health-check`, { method: "POST" });
showToast("健康检查已完成");
showToast(`健康检查已完成,ID: ${channelId}`);
await loadChannels();
return;
}
@@ -325,6 +334,7 @@ async function onTableClick(event) {
async function onSubmitForm(event) {
event.preventDefault();
const payload = {
channelType: elements.channelType.value,
providerCode: elements.providerCode.value,
@@ -337,21 +347,21 @@ async function onSubmitForm(event) {
};
const channelId = elements.channelId.value;
let savedChannel;
if (channelId) {
await request(`/admin/api/channels/${channelId}`, {
savedChannel = await request(`/admin/api/channels/${channelId}`, {
method: "PUT",
body: JSON.stringify(payload)
});
showToast("通道已更新");
} else {
await request("/admin/api/channels", {
savedChannel = await request("/admin/api/channels", {
method: "POST",
body: JSON.stringify(payload)
});
showToast("通道已创建");
}
resetForm();
showToast(`通道已保存,ID: ${savedChannel.id}`);
resetForm(savedChannel);
await loadChannels();
}
@@ -374,6 +384,7 @@ function syncTestFormVisibility() {
async function onSubmitTest(event) {
event.preventDefault();
let templateParams = {};
const rawTemplateParams = elements.testTemplateParams.value.trim();
if (rawTemplateParams) {
@@ -12,7 +12,7 @@
<div>
<p class="eyebrow">MessageHub Admin</p>
<h1>短信 / 邮件通道管理</h1>
<p class="subtitle">在这里维护数据库通道配置、执行健康检查,并直接发送测试消息。</p>
<p class="subtitle">在这里维护数据库通道配置、执行健康检查,并直接发送测试消息。保存后会生成通道 ID,外围系统可在消息体中传入 `channelId` 指定通道。</p>
</div>
<div class="hero-actions">
<button id="refreshButton" class="ghost-button">刷新列表</button>
@@ -25,7 +25,7 @@
<div class="panel-header">
<div>
<h2>通道列表</h2>
<p>支持启停、默认通道切换与单通道健康检查。</p>
<p>支持启停、切换默认通道、执行健康检查,并直接查看每条通道对应的通道 ID。</p>
</div>
</div>
<div id="channelEmptyState" class="empty-state" hidden>暂无通道数据。</div>
@@ -52,7 +52,7 @@
<div class="panel-header">
<div>
<h2 id="formTitle">新增通道</h2>
<p id="formSubtitle">保存后即可加入发送主链路。</p>
<p id="formSubtitle">保存后会生成通道 ID,外围系统可在消息体中通过 channelId 指定该通道。</p>
</div>
<button id="resetButton" class="ghost-button small">重置</button>
</div>
@@ -71,7 +71,7 @@
</label>
<label>
<span>通道名称</span>
<input id="channelName" type="text" maxlength="100" required placeholder="例如:生产短信主通道">
<input id="channelName" type="text" maxlength="100" required placeholder="例如:生产验证码短信通道">
</label>
<label>
<span>备注</span>
@@ -98,7 +98,7 @@
<div class="panel-header">
<div>
<h2>测试发送</h2>
<p>支持按通道直接发测试短信或测试邮件。</p>
<p>支持按通道 ID 定向测试短信或邮件。业务系统正常发送时,不传 channelId 就会自动走默认通道。</p>
</div>
</div>
<form id="testForm" class="form-grid">
@@ -120,7 +120,7 @@
</label>
<label class="full-width">
<span>消息内容 / 说明</span>
<textarea id="testContent" rows="4" placeholder="短信 mock 会直接记录这里的内容;邮件会作为正文"></textarea>
<textarea id="testContent" rows="4" placeholder="短信 Mock 会直接记录这里的内容;邮件会作为正文"></textarea>
</label>
<label class="full-width test-only-sms">
<span>模板参数 JSON</span>
@@ -0,0 +1,53 @@
# 2026-03-23 MessageHub 通道 ID 指定发送
## 本次完成
- 消息体新增可选字段 `channelId`
- 不传 `channelId` 时,仍按原逻辑走默认通道
- 传入 `channelId` 时,按 `channelType + channelId` 精确匹配指定通道
- 后台管理页新增通道 ID 展示
- 通道保存成功后,页面提示中会直接返回通道 ID
## 后端行为
- 默认模式:
- 不传 `channelId`
- `MessageHub` 会从当前已启用同类型通道中选择默认通道
- 指定模式:
- 传入 `channelId`
- `MessageHub` 会校验:
- 通道是否存在
- 通道类型是否匹配
- 通道是否处于启用状态
## 外围系统接入方式
消息体新增可选字段:
```json
{
"receiver": "13800138000",
"channelType": "SMS",
"msgType": "VERIFICATION",
"templateCode": "SPUG0001",
"templateParams": {
"code": "123456"
},
"sourceSystem": "yuminail",
"uniqueId": "biz-uuid",
"channelId": 12
}
```
说明:
- `channelId` 不传:走默认通道
- `channelId` 传入:走指定通道
## 相关文件
- [MessageDTO.java](/E:/code/xiaowang/MessageHub/src/main/java/com/xiaowang/messagehub/dto/MessageDTO.java)
- [SmsDispatchRequest.java](/E:/code/xiaowang/MessageHub/src/main/java/com/xiaowang/messagehub/model/SmsDispatchRequest.java)
- [MessageChannelService.java](/E:/code/xiaowang/MessageHub/src/main/java/com/xiaowang/messagehub/service/channel/MessageChannelService.java)
- [app.js](/E:/code/xiaowang/MessageHub/src/main/resources/static/messagehub-admin/app.js)
- [index.html](/E:/code/xiaowang/MessageHub/src/main/resources/static/messagehub-admin/index.html)