From 55738e2f721036c72004e2d623c52262d5814b0a Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Mon, 13 Jul 2026 15:11:48 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=82=E9=85=8DMessageHub=E6=AD=A3=E5=BC=8Fi?= =?UTF-8?q?ngress=E6=8A=95=E9=80=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/config/MessageHubSmsProperties.java | 2 - .../impl/MessageHubClientServiceImpl.java | 170 +++++++++++++----- .../impl/MessageHubClientServiceImplTest.java | 152 +++++++++------- docs/运维配置与集成说明.md | 16 +- docs/项目变更记录.md | 10 +- 5 files changed, 237 insertions(+), 113 deletions(-) diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/config/MessageHubSmsProperties.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/config/MessageHubSmsProperties.java index 0b9c37e5..195ec6f2 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/config/MessageHubSmsProperties.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/config/MessageHubSmsProperties.java @@ -51,8 +51,6 @@ public class MessageHubSmsProperties { private Long channelId; - private String sendMethod; - private Map templates = new HashMap<>(); } } diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java index 8a6c9d8e..d3d9388e 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -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 entity = new HttpEntity<>(request, jsonHeaders(token)); + MessageHubMessageIdReserveRequest reserveRequest = new MessageHubMessageIdReserveRequest(); + reserveRequest.setSourceSystem(request.getSourceSystem()); + HttpEntity entity = new HttpEntity<>(reserveRequest, jsonHeaders(token)); Exception lastException = null; for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) { try { - ResponseEntity> response = restTemplate.exchange( + ResponseEntity> response = restTemplate.exchange( targetUrl, HttpMethod.POST, entity, - new ParameterizedTypeReference>() { + new ParameterizedTypeReference>() { } ); - 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> response, - MessageHubSubmitRequest request, - String targetUrl) { + private String readReservedMessageId(ResponseEntity> 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 body = response.getBody(); + MessageHubApiResponse 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> 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 platformParams(String sendMethod) { - Map 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 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 { diff --git a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java index fc320ffc..5fe035ea 100644 --- a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java +++ b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java @@ -1,5 +1,6 @@ package com.xiaowang.jayucloud.core.modules.integration.service.impl; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.core.config.BrandProperties; import com.xiaowang.jayucloud.core.config.MessageHubSmsProperties; @@ -11,17 +12,27 @@ import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsStatusVO; import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.http.MediaType; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; +import java.nio.charset.StandardCharsets; +import java.util.Map; + import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; @@ -45,6 +56,10 @@ class MessageHubClientServiceImplTest { @Mock private BrandProperties brandProperties; + @Mock + private RabbitTemplate rabbitTemplate; + + private ObjectMapper objectMapper; private RestTemplate restTemplate; private MockRestServiceServer mockServer; private MessageHubClientServiceImpl service; @@ -52,13 +67,15 @@ class MessageHubClientServiceImplTest { @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + objectMapper = new ObjectMapper(); restTemplate = new RestTemplate(); mockServer = MockRestServiceServer.createServer(restTemplate); service = new MessageHubClientServiceImpl( - new ObjectMapper(), + objectMapper, snowflakeIdGenerator, messageHubPushConfigService, restTemplate, + rabbitTemplate, brandProperties, smsProperties() ); @@ -67,40 +84,76 @@ class MessageHubClientServiceImplTest { ReflectionTestUtils.setField(service, "legacyAccessToken", "legacy-token"); ReflectionTestUtils.setField(service, "legacyVerifyTemplateCode", "100001"); when(snowflakeIdGenerator.nextIdString()).thenReturn("sms-message-1"); - when(brandProperties.getMessageTemplateName()).thenReturn("甲屿"); + when(brandProperties.getMessageTemplateName()).thenReturn("JayuCloud"); } @Test - void registerVerificationMessageSubmitsAliyunTemplateToMessageHub() { + void registerVerificationMessageSubmitsAliyunTemplateToMessageHub() throws Exception { String sceneCode = "USER_REGISTER_SMS_CODE"; when(messageHubPushConfigService.getEnabledConfig(sceneCode)) .thenReturn(aliyunConfig(sceneCode, "100001")); - expectAliyunSubmit("100001", "123456"); + expectMessageIdReserve("jayucloud-designer", DESIGNER_TOKEN); service.sendSmsVerificationCode(sceneCode, "13800138000", "123456", "WEB", MessageHubSmsChannel.ALIYUN); + Map body = verifyPublishedMessage(DESIGNER_TOKEN); + assertEquals("messagehub-message-1", body.get("messageId")); + assertEquals("jayucloud-designer", body.get("sourceSystem")); + assertEquals("SMS", body.get("platform")); + assertEquals("13800138000", body.get("receiver")); + assertEquals("VERIFICATION", body.get("msgType")); + assertEquals("100001", body.get("templateCode")); + assertEquals(ALIYUN_CHANNEL_ID, ((Number) body.get("channelId")).longValue()); + assertEquals("sms-message-1", body.get("uniqueId")); + Map templateParams = mapAt(body, "templateParams"); + assertEquals("JayuCloud", templateParams.get("name")); + assertEquals("123456", templateParams.get("code")); + assertEquals("5", templateParams.get("min")); + assertEquals("5", templateParams.get("minutes")); + assertEquals("5", templateParams.get("number")); + assertNoSendMethod(body); mockServer.verify(); } @Test - void designerSpugVerificationMessageUsesTemplateOne() { + void designerSpugVerificationMessageUsesTemplateOne() throws Exception { String sceneCode = "USER_LOGIN_SMS_CODE"; when(messageHubPushConfigService.getEnabledConfig(sceneCode)).thenReturn(null); - expectDesignerSpugSubmit(sceneCode, "123456"); + expectMessageIdReserve("jayucloud-designer", DESIGNER_TOKEN); service.sendSmsVerificationCode(sceneCode, "13800138000", "123456", "WEB", MessageHubSmsChannel.SPUG); + Map body = verifyPublishedMessage(DESIGNER_TOKEN); + assertEquals("jayucloud-designer", body.get("sourceSystem")); + assertEquals("SPUG_SMS_VERIFY_1", body.get("templateCode")); + assertEquals(SPUG_CHANNEL_ID, ((Number) body.get("channelId")).longValue()); + Map templateParams = mapAt(body, "templateParams"); + assertEquals("JayuCloud", templateParams.get("name")); + assertEquals("123456", templateParams.get("code")); + assertEquals("5", templateParams.get("number")); + assertFalse(templateParams.containsKey("sceneCode")); + assertNoSendMethod(body); mockServer.verify(); } @Test - void salonSpugVerificationMessageUsesTemplateThreeWithName() { + void salonSpugVerificationMessageUsesTemplateThreeWithName() throws Exception { String sceneCode = "USER_LOGIN_SMS_CODE"; when(messageHubPushConfigService.getEnabledConfig(sceneCode)).thenReturn(null); - expectSalonSpugSubmit(sceneCode, "654321"); + expectMessageIdReserve("jayucloud-salon", SALON_TOKEN); service.sendSmsVerificationCode(sceneCode, "13800138000", "654321", "MANAGER_WEB", MessageHubSmsChannel.SPUG); + Map body = verifyPublishedMessage(SALON_TOKEN); + assertEquals("jayucloud-salon", body.get("sourceSystem")); + assertEquals("SPUG_SMS_VERIFY_3", body.get("templateCode")); + assertEquals(SPUG_CHANNEL_ID, ((Number) body.get("channelId")).longValue()); + Map templateParams = mapAt(body, "templateParams"); + assertEquals("JayuCloud", templateParams.get("name")); + assertEquals("654321", templateParams.get("code")); + assertEquals("5", templateParams.get("number")); + assertFalse(templateParams.containsKey("sceneCode")); + assertNoSendMethod(body); mockServer.verify(); } @@ -132,69 +185,45 @@ class MessageHubClientServiceImplTest { mockServer.verify(); } - private void expectAliyunSubmit(String templateCode, String code) { - mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages")) + private void expectMessageIdReserve(String sourceSystem, String accessToken) { + mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages/ids")) .andExpect(method(org.springframework.http.HttpMethod.POST)) - .andExpect(header("X-MessageHub-Access-Token", DESIGNER_TOKEN)) - .andExpect(jsonPath("$.sourceSystem", is("jayucloud-designer"))) - .andExpect(jsonPath("$.platform", is("SMS"))) - .andExpect(jsonPath("$.receiver", is("13800138000"))) - .andExpect(jsonPath("$.msgType", is("VERIFICATION"))) - .andExpect(jsonPath("$.templateCode", is(templateCode))) - .andExpect(jsonPath("$.channelId", is(ALIYUN_CHANNEL_ID))) - .andExpect(jsonPath("$.uniqueId", is("sms-message-1"))) - .andExpect(jsonPath("$.templateParams.name", is("甲屿"))) - .andExpect(jsonPath("$.templateParams.code", is(code))) - .andExpect(jsonPath("$.templateParams.min", is("5"))) - .andExpect(jsonPath("$.templateParams.minutes", is("5"))) - .andExpect(jsonPath("$.templateParams.number", is("5"))) - .andExpect(jsonPath("$.platformParams.sendMethod", is("OTHER"))) - .andRespond(successSubmit()); + .andExpect(header("X-MessageHub-Access-Token", accessToken)) + .andExpect(jsonPath("$.sourceSystem", is(sourceSystem))) + .andRespond(messageIdReserved()); } - private void expectDesignerSpugSubmit(String sceneCode, String code) { - mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages")) - .andExpect(method(org.springframework.http.HttpMethod.POST)) - .andExpect(header("X-MessageHub-Access-Token", DESIGNER_TOKEN)) - .andExpect(jsonPath("$.sourceSystem", is("jayucloud-designer"))) - .andExpect(jsonPath("$.templateCode", is("SPUG_SMS_VERIFY_1"))) - .andExpect(jsonPath("$.channelId", is(SPUG_CHANNEL_ID))) - .andExpect(jsonPath("$.templateParams.name", is("甲屿"))) - .andExpect(jsonPath("$.templateParams.code", is(code))) - .andExpect(jsonPath("$.templateParams.number", is("五"))) - .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("sceneCode")))) - .andExpect(jsonPath("$.platformParams.sendMethod", is("SPUG"))) - .andRespond(successSubmit()); + private Map verifyPublishedMessage(String accessToken) throws Exception { + ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); + verify(rabbitTemplate).send(eq("messagehub.ingress.exchange"), eq("message.send"), messageCaptor.capture()); + Message message = messageCaptor.getValue(); + assertEquals("messagehub-message-1", message.getMessageProperties().getMessageId()); + assertEquals(MessageProperties.CONTENT_TYPE_JSON, message.getMessageProperties().getContentType()); + assertEquals(StandardCharsets.UTF_8.name(), message.getMessageProperties().getContentEncoding()); + assertEquals(accessToken, message.getMessageProperties().getHeaders().get("X-MessageHub-Access-Token")); + String body = new String(message.getBody(), StandardCharsets.UTF_8); + return objectMapper.readValue(body, new TypeReference>() { + }); } - private void expectSalonSpugSubmit(String sceneCode, String code) { - mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages")) - .andExpect(method(org.springframework.http.HttpMethod.POST)) - .andExpect(header("X-MessageHub-Access-Token", SALON_TOKEN)) - .andExpect(jsonPath("$.sourceSystem", is("jayucloud-salon"))) - .andExpect(jsonPath("$.templateCode", is("SPUG_SMS_VERIFY_3"))) - .andExpect(jsonPath("$.channelId", is(SPUG_CHANNEL_ID))) - .andExpect(jsonPath("$.templateParams.name", is("甲屿"))) - .andExpect(jsonPath("$.templateParams.code", is(code))) - .andExpect(jsonPath("$.templateParams.number", is("五"))) - .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("sceneCode")))) - .andExpect(jsonPath("$.platformParams.sendMethod", is("SPUG"))) - .andRespond(successSubmit()); + private Map mapAt(Map body, String key) { + Object value = body.get(key); + assertTrue(value instanceof Map); + return (Map) value; } - private org.springframework.test.web.client.ResponseCreator successSubmit() { + private void assertNoSendMethod(Map body) { + assertFalse(mapAt(body, "platformParams").containsKey("sendMethod")); + } + + private org.springframework.test.web.client.ResponseCreator messageIdReserved() { return withSuccess(""" { "code": 0, "message": "success", "data": { "messageId": "messagehub-message-1", - "sourceSystem": "jayucloud-designer", - "uniqueId": "sms-message-1", - "platform": "SMS", - "dispatchStatus": "ACCEPTED", - "idempotentHit": false, - "outboxStatus": "PENDING" + "dispatchStatus": "ACCEPTED" } } """, MediaType.APPLICATION_JSON); @@ -209,7 +238,6 @@ class MessageHubClientServiceImplTest { config.setSourceSystem("jayucloud"); config.setTemplateCode(templateCode); config.setChannelId(ALIYUN_CHANNEL_ID); - config.setSendMethod("OTHER"); config.setEnabled(1); config.setIsDelete(0); return config; @@ -218,15 +246,13 @@ class MessageHubClientServiceImplTest { private MessageHubSmsProperties smsProperties() { MessageHubSmsProperties properties = new MessageHubSmsProperties(); properties.setDefaultChannel("ALIYUN"); - properties.setValidMinutesText("五"); + properties.setValidMinutesText("5"); properties.getClients().getDesigner().setSourceSystem("jayucloud-designer"); properties.getClients().getDesigner().setAccessToken(DESIGNER_TOKEN); properties.getClients().getSalon().setSourceSystem("jayucloud-salon"); properties.getClients().getSalon().setAccessToken(SALON_TOKEN); properties.getChannels().getAliyun().setChannelId(ALIYUN_CHANNEL_ID); - properties.getChannels().getAliyun().setSendMethod("OTHER"); properties.getChannels().getSpug().setChannelId(SPUG_CHANNEL_ID); - properties.getChannels().getSpug().setSendMethod("SPUG"); return properties; } } diff --git a/docs/运维配置与集成说明.md b/docs/运维配置与集成说明.md index 346bd82f..a69eb1da 100644 --- a/docs/运维配置与集成说明.md +++ b/docs/运维配置与集成说明.md @@ -783,6 +783,9 @@ JayuCloud 验证码短信通过 Nacos `messagehub.sms` 配置首发默认通道 messagehub: client: base-url: https://messagehub.example.com + ingress: + exchange: messagehub.ingress.exchange + routing-key: message.send sms: default-channel: ALIYUN valid-minutes-text: 五 @@ -796,7 +799,6 @@ messagehub: channels: aliyun: channel-id: - send-method: OTHER templates: USER_LOGIN_SMS_CODE: "100001" USER_REGISTER_SMS_CODE: "100001" @@ -806,7 +808,6 @@ messagehub: USER_VERIFY_BIND_PHONE_SMS_CODE: "100005" spug: channel-id: - send-method: SPUG templates: USER_LOGIN_SMS_CODE: SPUG_SMS_VERIFY_1 USER_REGISTER_SMS_CODE: SPUG_SMS_VERIFY_1 @@ -816,19 +817,22 @@ messagehub: - `default-channel` 支持 `ALIYUN` 或 `SPUG`,只决定首次发送和无历史记录时的起点。 - 设计师 Web/小程序分别传 `WEB`、`WECHAT_MINI`,使用 `clients.designer`;店务 Web/小程序分别传 `MANAGER_WEB`、`SALON_WECHAT_MINI`,使用 `clients.salon`。 - SPUG 设计师端默认使用 `SPUG_SMS_VERIFY_1`,参数为 `name`、`code`、`number`;店务端默认使用 `SPUG_SMS_VERIFY_3`,参数同样为 `name`、`code`、`number`。 -- Core 启动时会校验 `base-url`、设计师/店务来源系统、默认通道和兜底通道 `channel-id`/`send-method`、SPUG `name` 和 `valid-minutes-text`,缺失时启动失败并提示具体配置项。 +- Core 启动时会校验 `base-url`、MessageHub ingress exchange/routing-key、设计师/店务来源系统、默认通道和兜底通道 `channel-id`、SPUG `name` 和 `valid-minutes-text`,缺失时启动失败并提示具体配置项。 +- 正式短信发送链路为先调用 `POST /api/v1/messages/ids` 预取 `messageId`,再向 RabbitMQ `messagehub.ingress.exchange` 使用路由键 `message.send` 投递 JSON;AMQP header 必须携带 `X-MessageHub-Access-Token`。 +- MessageHub 最新短信契约不再接收 `sendMethod`,短信 `platformParams` 保持空对象。 - 用户允许重发时,Core 会先用上一条 `messageId` 查询 MessageHub 状态;只有 `SUCCESS` 算成功并沿用上一条通道,`FAILED`、`ACCEPTED`、`PENDING` 或查不到都作废旧验证码并切换到另一个通道。 - 状态查询发生网络、鉴权或非 not found 业务异常时不生成新验证码,直接返回明确错误,避免不确定状态下重复下发。 - MessageHub 管理端需要为两个来源系统授予 SMS 权限,并允许阿里云与 SPUG 对应 `channel-id`;SPUG 通道必须已配置 `baseUrl`、`apiKey` 和模板 externalId。 -#### 2026-07-12 开发环境当前配置 +#### 2026-07-13 开发环境当前配置 - Nacos 位置:`192.168.5.103:8848`,namespace `JayuCloud-Dev`,group `DEFAULT_GROUP`。 - `core.yaml`:`messagehub.client.base-url` 指向 `http://192.168.5.58:8080`。 +- `core.yaml`:`messagehub.ingress.exchange` 为 `messagehub.ingress.exchange`,`messagehub.ingress.routing-key` 为 `message.send`。 - `core.yaml`:`messagehub.sms.default-channel` 为 `SPUG`,`messagehub.sms.valid-minutes-text` 为 `5`。 - `core.yaml`:设计师端 `messagehub.sms.clients.designer.source-system` 为 `jayucloud-artist`;店务端 `messagehub.sms.clients.salon.source-system` 为 `jayucloud-salon`。 -- `core.yaml`:阿里云短信通道 `messagehub.sms.channels.aliyun.channel-id` 为 `333888327111634944`,`send-method` 为 `OTHER`。 -- `core.yaml`:SPUG 短信通道 `messagehub.sms.channels.spug.channel-id` 为 `334278054813855744`,`send-method` 为 `SPUG`。 +- `core.yaml`:阿里云短信通道 `messagehub.sms.channels.aliyun.channel-id` 为 `333888327111634944`。 +- `core.yaml`:SPUG 短信通道 `messagehub.sms.channels.spug.channel-id` 为 `334278054813855744`。 - `secret.yaml`:设计师端和店务端的 `messagehub.sms.clients.*.access-token` 已配置,本文档不记录明文。 - 验证方式:通过 Nacos API 读取 `core.yaml` 和 `secret.yaml` 后仅输出脱敏摘要,确认上述字段存在且两个 token 均为 46 位。 diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index be4fc72d..03fa1890 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -108,7 +108,7 @@ ## 2026-07-12 开发环境 MessageHub 短信通道配置补齐 - 变更原因:开发环境 `core.yaml` 仍停留在旧 `messagehub.client` 单通道配置,`messagehub.sms.channels.aliyun.channel-id` 等新多通道配置缺失,导致 JY-Core 启动时报 `MessageHub ALIYUN 短信通道 channelId 未配置`。 -- 处理方式:在开发 Nacos `JayuCloud-Dev/DEFAULT_GROUP` 中补齐 `core.yaml` 的 MessageHub 地址、`messagehub.sms.default-channel`、设计师/店务来源系统、阿里云与 SPUG 通道 ID 和 `send-method`;在 `secret.yaml` 中补齐两个来源系统的 `access-token`,密钥明文不写入仓库。 +- 处理方式:在开发 Nacos `JayuCloud-Dev/DEFAULT_GROUP` 中补齐 `core.yaml` 的 MessageHub 地址、`messagehub.sms.default-channel`、设计师/店务来源系统、阿里云与 SPUG 通道 ID;在 `secret.yaml` 中补齐两个来源系统的 `access-token`,密钥明文不写入仓库。 - 影响范围:仅影响开发环境 Nacos 配置中心中的 `core.yaml` 和 `secret.yaml`;不修改业务代码、不修改数据库、不修改初始化 SQL。 - 验证方式:通过 Nacos API 读取配置后仅输出脱敏摘要,确认 `core.yaml` 中 MessageHub 地址为 `192.168.5.58`,默认通道为 `SPUG`,阿里云通道 ID 为 `333888327111634944`,SPUG 通道 ID 为 `334278054813855744`;确认 `secret.yaml` 两个 `access-token` 均存在且长度为 46 位。 @@ -119,6 +119,14 @@ - 影响范围:仅影响 JY-Core 通过 MessageHub SPUG 通道发送短信验证码时的模板参数;不修改通道 ID、来源系统 token、数据库结构和初始化 SQL。 - 验证方式:运行 `MessageHubClientServiceImplTest`,覆盖店务端 SPUG 模板 `SPUG_SMS_VERIFY_3` 请求体包含 `templateParams.name`。 +## 2026-07-13 MessageHub 正式 ingress 投递适配 + +- 变更原因:MessageHub 对外接口文档更新,短信平台不再接收发送方式参数,正式业务投递入口改为“预取 `messageId` 后发布 RabbitMQ ingress”。 +- 处理方式:JY-Core 验证码短信先调用 `POST /api/v1/messages/ids` 获取 `messageId`,再向 `messagehub.ingress.exchange` 使用路由键 `message.send` 投递 JSON;AMQP header 携带 `X-MessageHub-Access-Token`;短信 `platformParams` 保持空对象。 +- 配置说明:新增 `messagehub.ingress.exchange` 和 `messagehub.ingress.routing-key`,删除开发 Nacos 中短信通道的旧发送方式配置依赖;密钥和 token 仍只保留在 Nacos/secret 配置中心。 +- 影响范围:仅影响 JY-Core 通过 MessageHub 发送验证码短信的提交链路和开发环境 Nacos `core.yaml`;状态查询接口、前端请求体、短信模板参数、数据库结构和初始化 SQL 不变。 +- 验证方式:运行 `MessageHubClientServiceImplTest`、`VerificationCodeServiceImplTest`;通过 Nacos API 回读 dev `core.yaml` 时仅输出脱敏摘要,确认 ingress 配置存在且旧发送方式配置已移除。 + ## 2026-07-12 文件上传统一对象存储编排链路 - 变更原因:用户确认所有文件相关上传都必须根据对象存储配置选择统一主存储,例如 `MINIO` 排第一时先写 MinIO,其他启用 Provider 作为副本补齐;此前头像、资料图片和评价图片仍可能绕过统一编排直接调用旧主存储。