适配MessageHub正式ingress投递

This commit is contained in:
2026-07-13 15:11:48 +08:00
parent 2725d9c1fe
commit 55738e2f72
5 changed files with 237 additions and 113 deletions
@@ -51,8 +51,6 @@ public class MessageHubSmsProperties {
private Long channelId;
private String sendMethod;
private Map<String, String> templates = new HashMap<>();
}
}
@@ -15,6 +15,11 @@ import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
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.core.ParameterizedTypeReference;
@@ -31,6 +36,8 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@@ -52,11 +59,14 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
private static final String DEFAULT_ALIYUN_TEMPLATE_CODE = "100001";
private static final String DESIGNER_SPUG_TEMPLATE_CODE = "SPUG_SMS_VERIFY_1";
private static final String SALON_SPUG_TEMPLATE_CODE = "SPUG_SMS_VERIFY_3";
private static final String DEFAULT_INGRESS_EXCHANGE = "messagehub.ingress.exchange";
private static final String DEFAULT_INGRESS_ROUTING_KEY = "message.send";
private final ObjectMapper objectMapper;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private final MessageHubPushConfigService messageHubPushConfigService;
private final RestTemplate restTemplate;
private final RabbitTemplate rabbitTemplate;
private final BrandProperties brandProperties;
private final MessageHubSmsProperties smsProperties;
@@ -72,9 +82,17 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
@Value("${messagehub.client.verify-template-code:100001}")
private String legacyVerifyTemplateCode;
@Value("${messagehub.ingress.exchange:messagehub.ingress.exchange}")
private String ingressExchange;
@Value("${messagehub.ingress.routing-key:message.send}")
private String ingressRoutingKey;
@PostConstruct
public void validateStartupConfiguration() {
requireText(baseUrl, "MessageHub API 地址未配置:messagehub.client.base-url");
requireText(resolveIngressExchange(), "MessageHub ingress exchange 未配置:messagehub.ingress.exchange");
requireText(resolveIngressRoutingKey(), "MessageHub ingress routing-key 未配置:messagehub.ingress.routing-key");
MessageHubSmsChannel defaultChannel = MessageHubSmsChannel.fromCode(smsProperties.getDefaultChannel(), MessageHubSmsChannel.ALIYUN);
requireChannelConfig(defaultChannel);
requireChannelConfig(defaultChannel.opposite());
@@ -197,78 +215,130 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
request.setUniqueId(uniqueId);
request.setChannelId(resolveChannelId(databaseConfig, channelConfig));
request.setTemplateParams(templateParams(sceneCode, code, clientGroup, channel));
request.setPlatformParams(platformParams(resolveSendMethod(databaseConfig, channelConfig, channel)));
return request;
}
private MessageHubSubmitResponse submitMessage(MessageHubSubmitRequest request, String token) {
requireText(baseUrl, "MessageHub API 地址未配置:messagehub.client.base-url");
requireText(token, "MessageHub 来源系统访问令牌未配置");
String messageId = reserveMessageId(request, token);
request.setMessageId(messageId);
publishIngressMessage(request, token);
return acceptedSubmitResponse(request);
}
private String reserveMessageId(MessageHubSubmitRequest request, String token) {
String targetUrl = UriComponentsBuilder.fromHttpUrl(baseUrl.trim())
.path("/api/v1/messages")
.path("/api/v1/messages/ids")
.build()
.toUriString();
HttpEntity<MessageHubSubmitRequest> entity = new HttpEntity<>(request, jsonHeaders(token));
MessageHubMessageIdReserveRequest reserveRequest = new MessageHubMessageIdReserveRequest();
reserveRequest.setSourceSystem(request.getSourceSystem());
HttpEntity<MessageHubMessageIdReserveRequest> entity = new HttpEntity<>(reserveRequest, jsonHeaders(token));
Exception lastException = null;
for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) {
try {
ResponseEntity<MessageHubApiResponse<MessageHubSubmitResponse>> response = restTemplate.exchange(
ResponseEntity<MessageHubApiResponse<MessageHubMessageIdReserveResponse>> response = restTemplate.exchange(
targetUrl,
HttpMethod.POST,
entity,
new ParameterizedTypeReference<MessageHubApiResponse<MessageHubSubmitResponse>>() {
new ParameterizedTypeReference<MessageHubApiResponse<MessageHubMessageIdReserveResponse>>() {
}
);
return readSubmitResponse(response, request, targetUrl);
return readReservedMessageId(response, request, targetUrl);
} catch (RestClientResponseException exception) {
lastException = exception;
log.warn("MessageHub API 调用失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, statusCode: {}, responseBody: {}",
log.warn("MessageHub messageId 预取失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, statusCode: {}, responseBody: {}",
attempt, targetUrl, request.getSourceSystem(), request.getUniqueId(),
exception.getRawStatusCode(), limitText(exception.getResponseBodyAsString()));
} catch (RestClientException exception) {
lastException = exception;
log.warn("MessageHub API 调用失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, reason: {}",
log.warn("MessageHub messageId 预取失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, reason: {}",
attempt, targetUrl, request.getSourceSystem(), request.getUniqueId(), exception.getMessage());
}
sleepBeforeRetry(attempt);
}
throw new BusinessException("MessageHub API 调用失败:url=" + targetUrl
throw new BusinessException("MessageHub messageId 预取失败:url=" + targetUrl
+ ", sourceSystem=" + request.getSourceSystem()
+ ", uniqueId=" + request.getUniqueId()
+ ", reason=" + (lastException == null ? "unknown" : lastException.getMessage()), lastException);
}
private MessageHubSubmitResponse readSubmitResponse(ResponseEntity<MessageHubApiResponse<MessageHubSubmitResponse>> response,
MessageHubSubmitRequest request,
String targetUrl) {
private String readReservedMessageId(ResponseEntity<MessageHubApiResponse<MessageHubMessageIdReserveResponse>> response,
MessageHubSubmitRequest request,
String targetUrl) {
if (!response.getStatusCode().is2xxSuccessful()) {
throw new BusinessException("MessageHub API 返回非成功状态:url=" + targetUrl
throw new BusinessException("MessageHub messageId 预取返回非成功状态:url=" + targetUrl
+ ", statusCode=" + response.getStatusCodeValue()
+ ", sourceSystem=" + request.getSourceSystem()
+ ", uniqueId=" + request.getUniqueId());
}
MessageHubApiResponse<MessageHubSubmitResponse> body = response.getBody();
MessageHubApiResponse<MessageHubMessageIdReserveResponse> body = response.getBody();
if (body == null) {
throw new BusinessException("MessageHub API 返回空响应:url=" + targetUrl
throw new BusinessException("MessageHub messageId 预取返回空响应:url=" + targetUrl
+ ", sourceSystem=" + request.getSourceSystem()
+ ", uniqueId=" + request.getUniqueId());
}
if (body.getCode() != 0) {
throw new BusinessException("MessageHub API 返回业务失败:url=" + targetUrl
throw new BusinessException("MessageHub messageId 预取返回业务失败:url=" + targetUrl
+ ", sourceSystem=" + request.getSourceSystem()
+ ", uniqueId=" + request.getUniqueId()
+ ", code=" + body.getCode()
+ ", message=" + body.getMessage());
}
MessageHubSubmitResponse data = body.getData();
MessageHubMessageIdReserveResponse data = body.getData();
if (data == null || !StringUtils.hasText(data.getMessageId())) {
throw new BusinessException("MessageHub API 返回缺少 messageId:url=" + targetUrl
throw new BusinessException("MessageHub messageId 预取返回缺少 messageId:url=" + targetUrl
+ ", sourceSystem=" + request.getSourceSystem()
+ ", uniqueId=" + request.getUniqueId()
+ ", response=" + limitText(toJson(body)));
}
return data;
return data.getMessageId();
}
private void publishIngressMessage(MessageHubSubmitRequest request, String token) {
String exchange = resolveIngressExchange();
String routingKey = resolveIngressRoutingKey();
byte[] body = writeMessageBody(request);
Message message = MessageBuilder.withBody(body)
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
.setMessageId(request.getMessageId())
.setTimestamp(new Date())
.build();
message.getMessageProperties().setContentEncoding(StandardCharsets.UTF_8.name());
message.getMessageProperties().setHeader(ACCESS_TOKEN_HEADER, token.trim());
Exception lastException = null;
for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) {
try {
rabbitTemplate.send(exchange, routingKey, message);
return;
} catch (AmqpException exception) {
lastException = exception;
log.warn("MessageHub ingress MQ 投递失败,attempt: {}, exchange: {}, routingKey: {}, sourceSystem: {}, uniqueId: {}, messageId: {}, reason: {}",
attempt, exchange, routingKey, request.getSourceSystem(), request.getUniqueId(),
request.getMessageId(), exception.getMessage());
}
sleepBeforeRetry(attempt);
}
throw new BusinessException("MessageHub ingress MQ 投递失败:exchange=" + exchange
+ ", routingKey=" + routingKey
+ ", sourceSystem=" + request.getSourceSystem()
+ ", uniqueId=" + request.getUniqueId()
+ ", messageId=" + request.getMessageId()
+ ", reason=" + (lastException == null ? "unknown" : lastException.getMessage()), lastException);
}
private MessageHubSubmitResponse acceptedSubmitResponse(MessageHubSubmitRequest request) {
MessageHubSubmitResponse response = new MessageHubSubmitResponse();
response.setMessageId(request.getMessageId());
response.setSourceSystem(request.getSourceSystem());
response.setUniqueId(request.getUniqueId());
response.setPlatform(request.getPlatform());
response.setDispatchStatus("ACCEPTED");
response.setOutboxStatus("PENDING");
return response;
}
private MessageHubSmsStatusVO readStatusResponse(ResponseEntity<MessageHubApiResponse<MessageHubStatusResponse>> response,
@@ -369,7 +439,6 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
if (channelConfig.getChannelId() == null) {
throw new BusinessException("MessageHub " + channel.name() + " 短信通道 channelId 未配置");
}
requireText(channelConfig.getSendMethod(), "MessageHub " + channel.name() + " 短信通道 sendMethod 未配置");
}
private String resolveTemplateCode(String sceneCode,
@@ -407,21 +476,6 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
return null;
}
private String resolveSendMethod(MessageHubPushConfigDO databaseConfig,
MessageHubSmsProperties.ChannelDetailProperties channelConfig,
MessageHubSmsChannel channel) {
if (StringUtils.hasText(channelConfig.getSendMethod())) {
return channelConfig.getSendMethod().trim().toUpperCase(Locale.ROOT);
}
if (databaseConfig != null && StringUtils.hasText(databaseConfig.getSendMethod())) {
return databaseConfig.getSendMethod().trim().toUpperCase(Locale.ROOT);
}
if (channel == MessageHubSmsChannel.SPUG) {
return "SPUG";
}
return "OTHER";
}
private String resolvePlatform(MessageHubPushConfigDO databaseConfig) {
if (databaseConfig != null && StringUtils.hasText(databaseConfig.getPlatform())) {
return databaseConfig.getPlatform();
@@ -455,12 +509,6 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
return params;
}
private Map<String, String> platformParams(String sendMethod) {
Map<String, String> params = new HashMap<>();
params.put("sendMethod", StringUtils.hasText(sendMethod) ? sendMethod : "OTHER");
return params;
}
private HttpHeaders jsonHeaders(String token) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
@@ -469,6 +517,20 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
return headers;
}
private String resolveIngressExchange() {
if (StringUtils.hasText(ingressExchange)) {
return ingressExchange.trim();
}
return DEFAULT_INGRESS_EXCHANGE;
}
private String resolveIngressRoutingKey() {
if (StringUtils.hasText(ingressRoutingKey)) {
return ingressRoutingKey.trim();
}
return DEFAULT_INGRESS_ROUTING_KEY;
}
private String normalizeSceneCode(String sceneCode) {
if (!StringUtils.hasText(sceneCode)) {
return "";
@@ -542,6 +604,16 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
}
}
private byte[] writeMessageBody(MessageHubSubmitRequest request) {
try {
return objectMapper.writeValueAsBytes(request);
} catch (Exception exception) {
throw new BusinessException("MessageHub ingress 消息序列化失败:sourceSystem=" + request.getSourceSystem()
+ ", uniqueId=" + request.getUniqueId()
+ ", messageId=" + request.getMessageId(), exception);
}
}
private String limitText(String value) {
if (value == null) {
return "";
@@ -561,6 +633,8 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
@Data
private static class MessageHubSubmitRequest {
private String messageId;
private String sourceSystem;
private String platform;
@@ -580,6 +654,20 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
private Map<String, String> platformParams = new HashMap<>();
}
@Data
private static class MessageHubMessageIdReserveRequest {
private String sourceSystem;
}
@Data
private static class MessageHubMessageIdReserveResponse {
private String messageId;
private String dispatchStatus;
}
@Data
private static class MessageHubApiResponse<T> {