接入MessageHub标准MQ验证码投递 #43

Merged
xiaowang merged 11 commits from dev into sit 2026-09-06 15:48:09 +08:00
4 changed files with 119 additions and 12 deletions
Showing only changes of commit 048c19e5fe - Show all commits
+13
View File
@@ -15,6 +15,7 @@ jobs:
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
MESSAGEHUB_ACCESS_TOKEN: ${{ secrets.MESSAGEHUB_SIT_ACCESS_TOKEN }}
WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit
steps:
- name: 从内网 Gitea 检出代码
@@ -75,6 +76,18 @@ jobs:
{"Name":"salon-web-sit","Host":"${WEB_TARGET_HOST}","Port":${WEB_TARGET_PORT},"User":"${WEB_TARGET_USER}","Purpose":"Salon SIT NGINX","Environment":"sit"}
]
JSON
- name: 写入 MessageHub 运行时 Token
shell: bash
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
MESSAGEHUB_ACCESS_TOKEN: ${{ secrets.MESSAGEHUB_SIT_ACCESS_TOKEN }}
run: |
set -euo pipefail
test -n "$SALON_PROD_SSH_PASSWORD"
test -n "$MESSAGEHUB_ACCESS_TOKEN"
printf 'MESSAGEHUB_ACCESS_TOKEN=%s\n' "$MESSAGEHUB_ACCESS_TOKEN" |
SSHPASS="$SALON_PROD_SSH_PASSWORD" sshpass -e ssh -o StrictHostKeyChecking=no -p 22 root@192.168.10.106 \
'install -d -m 700 /etc/sysconfig /etc/systemd/system/jc-salon-core-sit.service.d; install -m 600 /dev/stdin /etc/sysconfig/jc-salon-messagehub; printf "[Service]\\nEnvironmentFile=/etc/sysconfig/jc-salon-messagehub\\n" | install -m 644 /dev/stdin /etc/systemd/system/jc-salon-core-sit.service.d/messagehub.conf; systemctl daemon-reload'
- name: 自动发布 Salon SIT
shell: pwsh
env:
@@ -1,11 +1,11 @@
package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.xiaowang.jacyucloudsalon.core.config.BrandProperties;
import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.MessageHubPushConfigDO;
import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubClientService;
import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubPushConfigService;
import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
@@ -13,8 +13,13 @@ import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
@@ -35,14 +40,11 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
* Variable `rabbitTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final RabbitTemplate rabbitTemplate;
private final RestTemplate restTemplate;
/**
* Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ObjectMapper objectMapper;
/**
* Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
/**
* Variable `messageHubPushConfigService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -52,6 +54,18 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
*/
private final BrandProperties brandProperties;
@Value("${messagehub.client.base-url:http://192.168.10.107:8080}")
private String messageHubBaseUrl;
@Value("${messagehub.client.access-token:}")
private String messageHubAccessToken;
@Value("${messagehub.client.ingress-exchange:messagehub.ingress.exchange}")
private String ingressExchange;
@Value("${messagehub.client.ingress-routing-key:message.send}")
private String ingressRoutingKey;
@Value("${messagehub.client.sms-queue:smsQueue}")
/**
* Purpose: smsQueue supports MessageHubClientServiceImpl.java by holding or executing the sms queue business role.
@@ -59,7 +73,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
*/
private String smsQueue;
@Value("${messagehub.client.source-system:fingertipdesigner}")
@Value("${messagehub.client.source-system:jayucloud-salon}")
/**
* Purpose: sourceSystem supports MessageHubClientServiceImpl.java by holding or executing the source system business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
@@ -110,7 +124,8 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
public void sendSmsVerificationCode(String sceneCode, String phone, String code) {
try {
MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode);
String messageId = snowflakeIdGenerator.nextIdString();
String resolvedSourceSystem = resolveSourceSystem(config);
String messageId = reserveMessageId(resolvedSourceSystem);
Map<String, Object> messageBody = buildSmsMessageBody(config, sceneCode, phone, code, messageId);
String jsonBody = objectMapper.writeValueAsString(messageBody);
Message message = MessageBuilder
@@ -120,16 +135,68 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
.setMessageId(messageId)
.build();
String queueName = config == null ? smsQueue : config.getQueueName();
rabbitTemplate.convertAndSend(queueName, message);
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}",
sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
message.getMessageProperties().setHeader("X-MessageHub-Access-Token", requireAccessToken());
rabbitTemplate.send(ingressExchange, ingressRoutingKey, message);
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, exchange: {}, sourceSystem: {}, templateCode: {}",
sceneCode, phone, ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
} catch (Exception exception) {
log.error("发送短信验证码失败", exception);
throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception);
}
}
private String reserveMessageId(String resolvedSourceSystem) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-MessageHub-Access-Token", requireAccessToken());
Map<String, String> requestBody = Map.of("sourceSystem", resolvedSourceSystem);
ResponseEntity<JsonNode> response = restTemplate.postForEntity(
requireBaseUrl() + "/api/v1/messages/ids",
new HttpEntity<>(requestBody, headers),
JsonNode.class);
if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null) {
throw new IllegalStateException("MessageHub 预留消息 ID 失败,HTTP 状态: " + response.getStatusCode().value());
}
JsonNode body = response.getBody();
if (body.path("code").asInt(-1) != 0) {
throw new IllegalStateException("MessageHub 预留消息 ID 失败,响应码: " + body.path("code").asInt(-1)
+ ",原因: " + body.path("message").asText("未知错误"));
}
String messageId = body.path("data").path("messageId").asText("");
if (!StringUtils.hasText(messageId)) {
throw new IllegalStateException("MessageHub 预留消息 ID 响应缺少 data.messageId");
}
return messageId;
}
private String resolveSourceSystem(MessageHubPushConfigDO config) {
if (config != null && StringUtils.hasText(config.getSourceSystem())) {
return config.getSourceSystem();
}
return requireSourceSystem();
}
private String requireBaseUrl() {
if (!StringUtils.hasText(messageHubBaseUrl)) {
throw new IllegalStateException("未配置 messagehub.client.base-url");
}
return messageHubBaseUrl.replaceAll("/$", "");
}
private String requireAccessToken() {
if (!StringUtils.hasText(messageHubAccessToken)) {
throw new IllegalStateException("未配置 messagehub.client.access-token");
}
return messageHubAccessToken;
}
private String requireSourceSystem() {
if (!StringUtils.hasText(sourceSystem)) {
throw new IllegalStateException("未配置 messagehub.client.source-system");
}
return sourceSystem;
}
/**
* Run business method `buildSmsMessageBody`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -152,7 +219,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
messageBody.put("templateCode", config == null ? verifyTemplateCode : config.getTemplateCode());
messageBody.put("sourceSystem", config == null ? sourceSystem : config.getSourceSystem());
messageBody.put("uniqueId", messageId);
messageBody.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER");
messageBody.put("platformParams", Map.of("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"));
if (config != null && config.getChannelId() != null) {
messageBody.put("channelId", config.getChannelId());
}
@@ -0,0 +1,19 @@
# Salon Core 接入 MessageHub 标准 MQ
## 运行时配置
在 SIT 或生产 Core 服务的 systemd 环境文件中配置以下非敏感项,并通过安全的运行时变量注入访问 Token:
```text
MESSAGEHUB_BASE_URL=http://<MessageHub地址>:8080
MESSAGEHUB_ACCESS_TOKEN=<仅运行时注入,不写入仓库>
MESSAGEHUB_INGRESS_EXCHANGE=messagehub.ingress.exchange
MESSAGEHUB_INGRESS_ROUTING_KEY=message.send
MESSAGEHUB_SOURCE_SYSTEM=jayucloud-salon
```
SIT 的 `core.yaml` 已将上述变量映射为 `messagehub.client.*` 配置项;Gitea Secret 名称为 `MESSAGEHUB_SIT_ACCESS_TOKEN`,工作流会把它写入 Core 专用的 `/etc/sysconfig/jc-salon-messagehub`,不写入仓库或 Nacos。短信发送流程先调用 `/api/v1/messages/ids` 预留消息 ID,再向 RabbitMQ ingress 交换机投递,并在 AMQP Header 中携带 `X-MessageHub-Access-Token`。
## 验证
验证时检查 Core 日志中仅出现场景、手机号、交换机和模板编码,不得输出 Token;再通过 MessageHub 状态接口确认消息进入 `ACCEPTED` 或后续成功状态。
@@ -90,6 +90,14 @@ fingertip-designer:
max-total-connections: 200
max-connections-per-route: 50
messagehub:
client:
base-url: ${MESSAGEHUB_BASE_URL:http://192.168.10.107:8080}
access-token: ${MESSAGEHUB_ACCESS_TOKEN:}
ingress-exchange: ${MESSAGEHUB_INGRESS_EXCHANGE:messagehub.ingress.exchange}
ingress-routing-key: ${MESSAGEHUB_INGRESS_ROUTING_KEY:message.send}
source-system: ${MESSAGEHUB_SOURCE_SYSTEM:jayucloud-salon}
object-storage:
provider-order:
- MINIO