接入MessageHub标准MQ验证码投递
发布 Nacos 配置 / publish (push) Successful in 34s

This commit is contained in:
2026-09-06 15:42:56 +08:00
parent a50b7b6c66
commit 048c19e5fe
4 changed files with 119 additions and 12 deletions
@@ -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());
}