重构:统一核心和消息中心的雪花 ID
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -43,4 +45,19 @@ public class MyBatisPlusConfig {
|
||||
|
||||
return interceptor; // 返回配置好的拦截器
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) {
|
||||
return new IdentifierGenerator() {
|
||||
@Override
|
||||
public Number nextId(Object entity) {
|
||||
return snowflakeIdGenerator.nextId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String nextUUID(Object entity) {
|
||||
return snowflakeIdGenerator.nextIdString();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import java.time.LocalDateTime;
|
||||
@TableName("message_channel_config")
|
||||
public class MessageChannelConfigDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("channel_type")
|
||||
|
||||
@@ -15,7 +15,7 @@ import java.time.LocalDateTime;
|
||||
@TableName("message") // MyBatis-Plus的表名注解,指定对应数据库表名为message
|
||||
public class MessageDO {
|
||||
// 主键ID,使用自增策略
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
// 消息内容字段
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import java.time.LocalDateTime;
|
||||
@TableName("message_source_system_channel")
|
||||
public class MessageSourceSystemChannelDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("system_id")
|
||||
|
||||
@@ -14,7 +14,7 @@ import java.time.LocalDateTime;
|
||||
@TableName("message_source_system")
|
||||
public class MessageSourceSystemDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("system_code")
|
||||
|
||||
@@ -15,7 +15,7 @@ import java.time.LocalDateTime;
|
||||
@TableName("push_template")
|
||||
public class PushTemplateDO {
|
||||
// 主键ID,自增长类型
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
// 模板代码,用于唯一标识一个模板
|
||||
|
||||
+43
-60
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.core.MessageBuilder;
|
||||
@@ -13,72 +14,62 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 消息生产者服务类
|
||||
* 使用RabbitMQ发送短信和邮件消息
|
||||
* 使用 RabbitMQ 发送短信、邮件、微信和推送消息。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MessageProducerService {
|
||||
|
||||
// RabbitMQ模板,用于发送消息
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
// 对象映射器,用于将对象转换为JSON字符串
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
/**
|
||||
* 发送短信消息
|
||||
* @param messageDTO 消息数据传输对象,包含短信相关信息
|
||||
* 发送短信消息。
|
||||
*/
|
||||
public void sendSmsMessage(SmsMessageDTO messageDTO) {
|
||||
try {
|
||||
// 生成唯一消息ID
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
// 将消息对象转换为JSON字符串
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
// 构建RabbitMQ消息对象
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
// 发送消息到短信队列
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"sms." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
// 记录消息发送日志
|
||||
log.info("短信消息已发送到队列,消息ID: {}, 手机号: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
// 记录错误日志并抛出运行时异常
|
||||
log.error("发送短信消息失败", e);
|
||||
throw new RuntimeException("发送短信消息失败: " + e.getMessage(), e);
|
||||
|
||||
log.info("短信消息已发送到队列,消息ID: {}, 手机号: {}, 消息类型: {}",
|
||||
messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception exception) {
|
||||
log.error("发送短信消息失败", exception);
|
||||
throw new RuntimeException("发送短信消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮件消息
|
||||
* @param messageDTO 消息数据传输对象,包含邮件相关信息
|
||||
* 发送邮件消息。
|
||||
*/
|
||||
public void sendEmailMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
@@ -92,24 +83,23 @@ public class MessageProducerService {
|
||||
message
|
||||
);
|
||||
|
||||
log.info("邮件消息已发送到队列,消息ID: {}, 收件人: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送邮件消息失败", e);
|
||||
throw new RuntimeException("发送邮件消息失败: " + e.getMessage(), e);
|
||||
log.info("邮件消息已发送到队列,消息ID: {}, 收件人: {}, 消息类型: {}",
|
||||
messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception exception) {
|
||||
log.error("发送邮件消息失败", exception);
|
||||
throw new RuntimeException("发送邮件消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送微信消息
|
||||
* @param messageDTO 消息数据传输对象,包含微信相关信息
|
||||
* 发送微信消息。
|
||||
*/
|
||||
public void sendWeChatMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
@@ -123,24 +113,23 @@ public class MessageProducerService {
|
||||
message
|
||||
);
|
||||
|
||||
log.info("微信消息已发送到队列,消息ID: {}, 接收者: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送微信消息失败", e);
|
||||
throw new RuntimeException("发送微信消息失败: " + e.getMessage(), e);
|
||||
log.info("微信消息已发送到队列,消息ID: {}, 接收者: {}, 消息类型: {}",
|
||||
messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception exception) {
|
||||
log.error("发送微信消息失败", exception);
|
||||
throw new RuntimeException("发送微信消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送推送消息
|
||||
* @param messageDTO 消息数据传输对象,包含推送相关信息
|
||||
* 发送推送消息。
|
||||
*/
|
||||
public void sendPushMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
@@ -154,25 +143,23 @@ public class MessageProducerService {
|
||||
message
|
||||
);
|
||||
|
||||
log.info("推送消息已发送到队列,消息ID: {}, 接收者: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送推送消息失败", e);
|
||||
throw new RuntimeException("发送推送消息失败: " + e.getMessage(), e);
|
||||
log.info("推送消息已发送到队列,消息ID: {}, 接收者: {}, 消息类型: {}",
|
||||
messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception exception) {
|
||||
log.error("发送推送消息失败", exception);
|
||||
throw new RuntimeException("发送推送消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用发送消息方法
|
||||
* 根据渠道类型自动路由到对应的队列
|
||||
* @param messageDTO 消息数据传输对象
|
||||
* 通用发送消息方法。
|
||||
*/
|
||||
public void sendMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
@@ -195,17 +182,13 @@ public class MessageProducerService {
|
||||
routingKey = "unknown." + messageDTO.getMsgType().toLowerCase();
|
||||
}
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
routingKey,
|
||||
message
|
||||
);
|
||||
rabbitTemplate.send(RabbitMQConfig.MESSAGE_EXCHANGE, routingKey, message);
|
||||
|
||||
log.info("消息已发送到队列,消息ID: {}, 渠道类型: {}, 接收者: {}, 消息类型: {}",
|
||||
log.info("消息已发送到队列,消息ID: {}, 渠道类型: {}, 接收者: {}, 消息类型: {}",
|
||||
messageId, channelType, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送消息失败", e);
|
||||
throw new RuntimeException("发送消息失败: " + e.getMessage(), e);
|
||||
} catch (Exception exception) {
|
||||
log.error("发送消息失败", exception);
|
||||
throw new RuntimeException("发送消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -6,6 +6,7 @@ import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.SmsSendResult;
|
||||
import com.xiaowang.messagehub.service.channel.ChannelEnvironmentService;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -14,9 +15,12 @@ import org.springframework.stereotype.Service;
|
||||
public class MockSmsChannelProvider implements SmsChannelProvider {
|
||||
|
||||
private final ChannelEnvironmentService environmentService;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
public MockSmsChannelProvider(ChannelEnvironmentService environmentService) {
|
||||
public MockSmsChannelProvider(ChannelEnvironmentService environmentService,
|
||||
TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) {
|
||||
this.environmentService = environmentService;
|
||||
this.snowflakeIdGenerator = snowflakeIdGenerator;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -42,7 +46,7 @@ public class MockSmsChannelProvider implements SmsChannelProvider {
|
||||
|
||||
SmsSendResult result = new SmsSendResult();
|
||||
result.setMessage("Mock 短信发送成功");
|
||||
result.setRequestId("MOCK-" + System.currentTimeMillis());
|
||||
result.setRequestId("MOCK-" + snowflakeIdGenerator.nextIdString());
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package com.xiaowang.messagehub.support.id;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 时间高位雪花 ID 生成器。
|
||||
* 用于消息中心主键、消息标识和有序业务编码生成。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class TimeOrderedSnowflakeIdGenerator {
|
||||
|
||||
private static final long DEFAULT_EPOCH = 1704067200000L;
|
||||
private static final long WORKER_ID_BITS = 5L;
|
||||
private static final long DATACENTER_ID_BITS = 5L;
|
||||
private static final long SEQUENCE_BITS = 12L;
|
||||
private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
|
||||
private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);
|
||||
private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
|
||||
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
|
||||
private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
|
||||
private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
|
||||
|
||||
private final long epoch;
|
||||
private final long workerId;
|
||||
private final long datacenterId;
|
||||
|
||||
private long sequence = 0L;
|
||||
private long lastTimestamp = -1L;
|
||||
|
||||
public TimeOrderedSnowflakeIdGenerator(
|
||||
@Value("${snowflake.epoch:" + DEFAULT_EPOCH + "}") long configuredEpoch,
|
||||
@Value("${snowflake.worker-id:-1}") long configuredWorkerId,
|
||||
@Value("${snowflake.datacenter-id:-1}") long configuredDatacenterId,
|
||||
@Value("${spring.application.name:message-hub}") String applicationName
|
||||
) {
|
||||
this.epoch = configuredEpoch > 0 ? configuredEpoch : DEFAULT_EPOCH;
|
||||
this.datacenterId = resolveNodeId(configuredDatacenterId, MAX_DATACENTER_ID, resolveDatacenterId());
|
||||
this.workerId = resolveNodeId(configuredWorkerId, MAX_WORKER_ID, resolveWorkerId(applicationName));
|
||||
log.info("Snowflake generator ready: app={}, epoch={}, datacenterId={}, workerId={}",
|
||||
applicationName, this.epoch, this.datacenterId, this.workerId);
|
||||
}
|
||||
|
||||
public synchronized long nextId() {
|
||||
long timestamp = currentTimeMillis();
|
||||
if (timestamp < lastTimestamp) {
|
||||
timestamp = waitUntil(lastTimestamp);
|
||||
}
|
||||
|
||||
if (timestamp == lastTimestamp) {
|
||||
sequence = (sequence + 1) & SEQUENCE_MASK;
|
||||
if (sequence == 0L) {
|
||||
timestamp = waitUntilNextMillis(lastTimestamp);
|
||||
}
|
||||
} else {
|
||||
sequence = 0L;
|
||||
}
|
||||
|
||||
lastTimestamp = timestamp;
|
||||
return ((timestamp - epoch) << TIMESTAMP_LEFT_SHIFT)
|
||||
| (datacenterId << DATACENTER_ID_SHIFT)
|
||||
| (workerId << WORKER_ID_SHIFT)
|
||||
| sequence;
|
||||
}
|
||||
|
||||
public String nextIdString() {
|
||||
return Long.toUnsignedString(nextId());
|
||||
}
|
||||
|
||||
public String nextBase36String(int width) {
|
||||
String raw = Long.toUnsignedString(nextId(), 36).toUpperCase(Locale.ROOT);
|
||||
if (raw.length() >= width) {
|
||||
return raw.substring(raw.length() - width);
|
||||
}
|
||||
return "0".repeat(width - raw.length()) + raw;
|
||||
}
|
||||
|
||||
private long currentTimeMillis() {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
|
||||
private long waitUntil(long targetTimestamp) {
|
||||
long timestamp = currentTimeMillis();
|
||||
while (timestamp < targetTimestamp) {
|
||||
Thread.yield();
|
||||
timestamp = currentTimeMillis();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
private long waitUntilNextMillis(long currentTimestamp) {
|
||||
long timestamp = currentTimeMillis();
|
||||
while (timestamp <= currentTimestamp) {
|
||||
Thread.yield();
|
||||
timestamp = currentTimeMillis();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
private long resolveNodeId(long configuredValue, long maxValue, long fallbackValue) {
|
||||
long candidate = configuredValue >= 0 ? configuredValue : fallbackValue;
|
||||
return Math.floorMod(candidate, maxValue + 1);
|
||||
}
|
||||
|
||||
private long resolveDatacenterId() {
|
||||
return stableHash(resolveMachineFingerprint());
|
||||
}
|
||||
|
||||
private long resolveWorkerId(String applicationName) {
|
||||
return stableHash(applicationName + ":" + resolveProcessFingerprint());
|
||||
}
|
||||
|
||||
private String resolveMachineFingerprint() {
|
||||
try {
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (interfaces != null && interfaces.hasMoreElements()) {
|
||||
NetworkInterface networkInterface = interfaces.nextElement();
|
||||
if (networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual()) {
|
||||
continue;
|
||||
}
|
||||
byte[] hardwareAddress = networkInterface.getHardwareAddress();
|
||||
if (hardwareAddress != null && hardwareAddress.length > 0) {
|
||||
return bytesToHex(hardwareAddress);
|
||||
}
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
log.warn("Unable to resolve hardware address for snowflake datacenter id", exception);
|
||||
}
|
||||
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (Exception exception) {
|
||||
log.warn("Unable to resolve host address for snowflake datacenter id", exception);
|
||||
return "fallback-host";
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveProcessFingerprint() {
|
||||
try {
|
||||
return ManagementFactory.getRuntimeMXBean().getName();
|
||||
} catch (Exception exception) {
|
||||
return "pid-unknown";
|
||||
}
|
||||
}
|
||||
|
||||
private long stableHash(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return 0L;
|
||||
}
|
||||
long hash = 1469598103934665603L;
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
for (byte currentByte : bytes) {
|
||||
hash ^= currentByte;
|
||||
hash *= 1099511628211L;
|
||||
}
|
||||
return hash & Long.MAX_VALUE;
|
||||
}
|
||||
|
||||
private String bytesToHex(byte[] source) {
|
||||
StringBuilder builder = new StringBuilder(source.length * 2);
|
||||
for (byte currentByte : source) {
|
||||
builder.append(String.format("%02X", currentByte));
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -38,4 +40,19 @@ public class MyBatisPlusConfig {
|
||||
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) {
|
||||
return new IdentifierGenerator() {
|
||||
@Override
|
||||
public Number nextId(Object entity) {
|
||||
return snowflakeIdGenerator.nextId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String nextUUID(Object entity) {
|
||||
return snowflakeIdGenerator.nextIdString();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -7,6 +7,7 @@ import com.xiaowang.yuminailcore.dto.ObjectStorageFileDTO;
|
||||
import com.xiaowang.yuminailcore.service.ChunkUploadService;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -18,8 +19,6 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 对象存储文件信息表 Controller
|
||||
* 对应数据库表 t_object_storage_file
|
||||
@@ -36,6 +35,7 @@ public class ObjectStorageFileController {
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final MinioService minioService;
|
||||
private final ChunkUploadService chunkUploadService;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@PostMapping("/upload/init")
|
||||
public Result<ChunkUploadSessionVO> initChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
|
||||
@@ -59,10 +59,10 @@ public class ObjectStorageFileController {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
|
||||
chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId());
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
String originalFilename = preparedUploadFile.getFileName();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = UUID.randomUUID() + fileExtension;
|
||||
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
String fileUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
|
||||
|
||||
@@ -98,7 +98,7 @@ public class ObjectStorageFileController {
|
||||
try {
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = UUID.randomUUID().toString() + fileExtension;
|
||||
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
String fileUrl = minioService.uploadFile(file, objectName);
|
||||
|
||||
|
||||
+5
-4
@@ -14,6 +14,7 @@ import com.xiaowang.yuminailcore.vo.UserVO;
|
||||
import com.xiaowang.yuminailcore.service.MinioService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.service.VerificationCodeService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.utils.AccountValidationUtils;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -24,7 +25,6 @@ import javax.validation.Valid;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -45,6 +45,7 @@ public class UserController {
|
||||
private final VerificationCodeService verificationCodeService;
|
||||
private final UserMapper userMapper;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
/**
|
||||
* 创建用户
|
||||
@@ -422,10 +423,10 @@ public class UserController {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
|
||||
chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId());
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
|
||||
String originalFilename = preparedUploadFile.getFileName();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = "avatar/" + userId + "/" + UUID.randomUUID() + fileExtension;
|
||||
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
String avatarUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
|
||||
userService.updateUserAvatar(userId, avatarUrl);
|
||||
@@ -450,7 +451,7 @@ public class UserController {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = "avatar/" + userId + "/" + UUID.randomUUID().toString() + fileExtension;
|
||||
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
String avatarUrl = minioService.uploadFile(file, objectName);
|
||||
userService.updateUserAvatar(userId, avatarUrl);
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ import java.time.LocalDateTime;
|
||||
@TableName("t_balance_change_detail")
|
||||
public class BalanceChangeDetailDO {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
|
||||
@@ -21,7 +21,7 @@ public abstract class BaseEntity {
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId(type = IdType.AUTO)
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
|
||||
+3
-2
@@ -17,6 +17,7 @@ import com.xiaowang.yuminailcore.mapper.TagMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.CouponVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
@@ -33,7 +34,6 @@ import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -61,6 +61,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
private final ShopMapper shopMapper;
|
||||
private final UserMapper userMapper;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@@ -608,7 +609,7 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, CouponDO> imple
|
||||
|
||||
private String generateUniqueManualCouponCode() {
|
||||
for (int attempt = 0; attempt < 10; attempt++) {
|
||||
String candidate = "CPN_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12).toUpperCase();
|
||||
String candidate = "CPN_" + snowflakeIdGenerator.nextBase36String(13);
|
||||
if (lambdaQuery().eq(CouponDO::getCouponCode, candidate).count() == 0) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
+5
-4
@@ -2,6 +2,7 @@ package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.yuminailcore.service.MessageHubClientService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -14,8 +15,6 @@ import org.springframework.stereotype.Service;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* MessageHub 客户端服务实现。
|
||||
* 通过 RabbitMQ 发送消息到 MessageHub 服务。
|
||||
@@ -28,6 +27,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@Value("${messagehub.client.sms-queue:smsQueue}")
|
||||
private String smsQueue;
|
||||
@@ -41,13 +41,14 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
@Override
|
||||
public void sendSmsVerificationCode(String phone, String code) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
Map<String, Object> messageBody = new HashMap<>();
|
||||
messageBody.put("receiver", phone);
|
||||
messageBody.put("channelType", "SMS");
|
||||
messageBody.put("msgType", "VERIFICATION");
|
||||
messageBody.put("templateCode", verifyTemplateCode);
|
||||
messageBody.put("sourceSystem", sourceSystem);
|
||||
messageBody.put("uniqueId", UUID.randomUUID().toString());
|
||||
messageBody.put("uniqueId", messageId);
|
||||
messageBody.put("sendMethod", "SPUG");
|
||||
|
||||
Map<String, Object> templateParams = new HashMap<>();
|
||||
@@ -61,7 +62,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
.withBody(jsonBody.getBytes(StandardCharsets.UTF_8))
|
||||
.setContentType("application/json")
|
||||
.setContentEncoding(StandardCharsets.UTF_8.name())
|
||||
.setMessageId(UUID.randomUUID().toString())
|
||||
.setMessageId(messageId)
|
||||
.build();
|
||||
|
||||
rabbitTemplate.convertAndSend(smsQueue, message);
|
||||
|
||||
-1
@@ -10,7 +10,6 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
|
||||
+5
-3
@@ -22,6 +22,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||
import com.xiaowang.yuminailcore.service.CouponService;
|
||||
import com.xiaowang.yuminailcore.service.OrderService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
import com.xiaowang.yuminailcore.vo.OrderItemVO;
|
||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||
@@ -44,7 +45,6 @@ import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -99,6 +99,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private UserShopBindingSupport userShopBindingSupport;
|
||||
|
||||
@Resource
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderVO createOrder(Long userId, OrderDTO orderDTO) {
|
||||
@@ -213,8 +216,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
}
|
||||
|
||||
String orderNo = "ORD" + LocalDateTime.now().format(ORDER_NO_TIME_FORMATTER)
|
||||
+ UUID.randomUUID().toString().substring(0, 8).toUpperCase();
|
||||
String orderNo = "ORD" + snowflakeIdGenerator.nextIdString();
|
||||
|
||||
OrderDO order = new OrderDO();
|
||||
order.setOrderNo(orderNo);
|
||||
|
||||
+4
-2
@@ -17,6 +17,7 @@ import com.xiaowang.yuminailcore.service.NailArtistInfoService;
|
||||
import com.xiaowang.yuminailcore.service.ShopService;
|
||||
import com.xiaowang.yuminailcore.service.UserService;
|
||||
import com.xiaowang.yuminailcore.service.VerificationCodeService;
|
||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.yuminailcore.support.PermissionPolicy;
|
||||
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||
@@ -77,6 +78,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
private final VerificationCodeService verificationCodeService;
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
private static Map<String, PermissionSeed> buildDefaultPermissionSeeds() {
|
||||
Map<String, PermissionSeed> seeds = new HashMap<>();
|
||||
@@ -1208,13 +1210,13 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
}
|
||||
|
||||
private String buildDeletedAccount(UserDO userDO) {
|
||||
String suffix = userDO.getId() + "_" + System.currentTimeMillis();
|
||||
String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString();
|
||||
String base = StringUtils.hasText(userDO.getAccount()) ? userDO.getAccount() : "deleted";
|
||||
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
|
||||
}
|
||||
|
||||
private String buildDeletedPhone(UserDO userDO) {
|
||||
String suffix = userDO.getId() + "_" + System.currentTimeMillis();
|
||||
String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString();
|
||||
String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone";
|
||||
return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50);
|
||||
}
|
||||
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package com.xiaowang.yuminailcore.support.id;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 时间高位雪花 ID 生成器。
|
||||
* 统一为数据库主键和业务有序标识提供趋势递增的唯一 ID。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class TimeOrderedSnowflakeIdGenerator {
|
||||
|
||||
private static final long DEFAULT_EPOCH = 1704067200000L;
|
||||
private static final long WORKER_ID_BITS = 5L;
|
||||
private static final long DATACENTER_ID_BITS = 5L;
|
||||
private static final long SEQUENCE_BITS = 12L;
|
||||
private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
|
||||
private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);
|
||||
private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
|
||||
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
|
||||
private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
|
||||
private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
|
||||
|
||||
private final long epoch;
|
||||
private final long workerId;
|
||||
private final long datacenterId;
|
||||
|
||||
private long sequence = 0L;
|
||||
private long lastTimestamp = -1L;
|
||||
|
||||
public TimeOrderedSnowflakeIdGenerator(
|
||||
@Value("${snowflake.epoch:" + DEFAULT_EPOCH + "}") long configuredEpoch,
|
||||
@Value("${snowflake.worker-id:-1}") long configuredWorkerId,
|
||||
@Value("${snowflake.datacenter-id:-1}") long configuredDatacenterId,
|
||||
@Value("${spring.application.name:yumi-nail-core}") String applicationName
|
||||
) {
|
||||
this.epoch = configuredEpoch > 0 ? configuredEpoch : DEFAULT_EPOCH;
|
||||
this.datacenterId = resolveNodeId(configuredDatacenterId, MAX_DATACENTER_ID, resolveDatacenterId());
|
||||
this.workerId = resolveNodeId(configuredWorkerId, MAX_WORKER_ID, resolveWorkerId(applicationName));
|
||||
log.info("Snowflake generator ready: app={}, epoch={}, datacenterId={}, workerId={}",
|
||||
applicationName, this.epoch, this.datacenterId, this.workerId);
|
||||
}
|
||||
|
||||
public synchronized long nextId() {
|
||||
long timestamp = currentTimeMillis();
|
||||
if (timestamp < lastTimestamp) {
|
||||
timestamp = waitUntil(lastTimestamp);
|
||||
}
|
||||
|
||||
if (timestamp == lastTimestamp) {
|
||||
sequence = (sequence + 1) & SEQUENCE_MASK;
|
||||
if (sequence == 0L) {
|
||||
timestamp = waitUntilNextMillis(lastTimestamp);
|
||||
}
|
||||
} else {
|
||||
sequence = 0L;
|
||||
}
|
||||
|
||||
lastTimestamp = timestamp;
|
||||
return ((timestamp - epoch) << TIMESTAMP_LEFT_SHIFT)
|
||||
| (datacenterId << DATACENTER_ID_SHIFT)
|
||||
| (workerId << WORKER_ID_SHIFT)
|
||||
| sequence;
|
||||
}
|
||||
|
||||
public String nextIdString() {
|
||||
return Long.toUnsignedString(nextId());
|
||||
}
|
||||
|
||||
public String nextBase36String(int width) {
|
||||
String raw = Long.toUnsignedString(nextId(), 36).toUpperCase(Locale.ROOT);
|
||||
if (raw.length() >= width) {
|
||||
return raw.substring(raw.length() - width);
|
||||
}
|
||||
return "0".repeat(width - raw.length()) + raw;
|
||||
}
|
||||
|
||||
private long currentTimeMillis() {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
|
||||
private long waitUntil(long targetTimestamp) {
|
||||
long timestamp = currentTimeMillis();
|
||||
while (timestamp < targetTimestamp) {
|
||||
Thread.yield();
|
||||
timestamp = currentTimeMillis();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
private long waitUntilNextMillis(long currentTimestamp) {
|
||||
long timestamp = currentTimeMillis();
|
||||
while (timestamp <= currentTimestamp) {
|
||||
Thread.yield();
|
||||
timestamp = currentTimeMillis();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
private long resolveNodeId(long configuredValue, long maxValue, long fallbackValue) {
|
||||
long candidate = configuredValue >= 0 ? configuredValue : fallbackValue;
|
||||
return Math.floorMod(candidate, maxValue + 1);
|
||||
}
|
||||
|
||||
private long resolveDatacenterId() {
|
||||
return stableHash(resolveMachineFingerprint());
|
||||
}
|
||||
|
||||
private long resolveWorkerId(String applicationName) {
|
||||
return stableHash(applicationName + ":" + resolveProcessFingerprint());
|
||||
}
|
||||
|
||||
private String resolveMachineFingerprint() {
|
||||
try {
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (interfaces != null && interfaces.hasMoreElements()) {
|
||||
NetworkInterface networkInterface = interfaces.nextElement();
|
||||
if (networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual()) {
|
||||
continue;
|
||||
}
|
||||
byte[] hardwareAddress = networkInterface.getHardwareAddress();
|
||||
if (hardwareAddress != null && hardwareAddress.length > 0) {
|
||||
return bytesToHex(hardwareAddress);
|
||||
}
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
log.warn("Unable to resolve hardware address for snowflake datacenter id", exception);
|
||||
}
|
||||
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (Exception exception) {
|
||||
log.warn("Unable to resolve host address for snowflake datacenter id", exception);
|
||||
return "fallback-host";
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveProcessFingerprint() {
|
||||
try {
|
||||
return ManagementFactory.getRuntimeMXBean().getName();
|
||||
} catch (Exception exception) {
|
||||
return "pid-unknown";
|
||||
}
|
||||
}
|
||||
|
||||
private long stableHash(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return 0L;
|
||||
}
|
||||
long hash = 1469598103934665603L;
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
for (byte currentByte : bytes) {
|
||||
hash ^= currentByte;
|
||||
hash *= 1099511628211L;
|
||||
}
|
||||
return hash & Long.MAX_VALUE;
|
||||
}
|
||||
|
||||
private String bytesToHex(byte[] source) {
|
||||
StringBuilder builder = new StringBuilder(source.length * 2);
|
||||
for (byte currentByte : source) {
|
||||
builder.append(String.format("%02X", currentByte));
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
# 2026-03-30 统一时间高位雪花 ID 收口重构
|
||||
|
||||
## 本轮目标
|
||||
|
||||
- 将 `YumiNail-Core`、`MessageHub` 中仍残留的 `UUID`、随机消息标识、伪唯一时间戳请求号统一收口到“时间戳高位”的雪花算法。
|
||||
- 统一数据库主键生成口径,避免出现一部分实体走数据库自增、一部分实体走雪花 ID 的混用状态。
|
||||
- 保持现有初始化 SQL 与空库部署链路可继续执行,不引入新的初始化门槛。
|
||||
|
||||
## 已完成内容
|
||||
|
||||
### 1. 统一主键生成器
|
||||
|
||||
- 新增统一雪花生成器:
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/id/TimeOrderedSnowflakeIdGenerator.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/support/id/TimeOrderedSnowflakeIdGenerator.java`
|
||||
- 生成规则采用时间戳高位,输出结果天然趋势递增,适合主键、订单号、消息号、对象名等有序场景。
|
||||
- 支持 `snowflake.epoch`、`snowflake.worker-id`、`snowflake.datacenter-id` 配置;未显式配置时自动根据机器指纹与进程信息推导节点号。
|
||||
|
||||
### 2. Core 主键与业务标识统一
|
||||
|
||||
- `MyBatisPlusConfig` 已接管 `IdentifierGenerator`,`nextId` 与 `nextUUID` 均改为统一雪花生成器输出。
|
||||
- `BaseEntity` 与 `BalanceChangeDetailDO` 改为 `IdType.ASSIGN_ID`,避免继续依赖数据库自增。
|
||||
- 下列业务标识已改为雪花生成:
|
||||
- 订单号:`ORD` + 雪花字符串
|
||||
- MessageHub 客户端消息 `messageId` / `uniqueId`
|
||||
- 对象存储文件名
|
||||
- 用户头像对象名
|
||||
- 自动生成优惠券编码
|
||||
- 删除账号、删除手机号占位后缀
|
||||
|
||||
### 3. MessageHub 主键与消息号统一
|
||||
|
||||
- `MessageChannelConfigDO`、`MessageDO`、`MessageSourceSystemDO`、`MessageSourceSystemChannelDO`、`PushTemplateDO` 已统一为 `IdType.ASSIGN_ID`。
|
||||
- `MessageProducerService` 中 5 处 `UUID.randomUUID()` 已全部替换为雪花字符串,发送到 MQ 的消息 ID 与业务 `uniqueId` 口径一致。
|
||||
- `MockSmsChannelProvider` 的 mock 请求号改为 `MOCK-` + 雪花字符串,避免仅靠毫秒时间戳拼接导致的碰撞风险。
|
||||
|
||||
### 4. 清理与校验
|
||||
|
||||
- 移除了 `MinioServiceImpl` 中已无用的 `UUID` 导入。
|
||||
- 全局复扫后,代码中已不存在运行时 `UUID.randomUUID()` 残留。
|
||||
- 保留未改项:
|
||||
- 雪花生成器内部的 `System.currentTimeMillis()`:这是算法时钟本身,必须保留。
|
||||
- `VerificationCodeServiceImpl` 的发送限流时间戳:这是业务限流,不是唯一 ID,不应替换为雪花。
|
||||
|
||||
## 本轮未改 SQL 的说明
|
||||
|
||||
- 本轮没有新增数据库字段,也没有变更表结构。
|
||||
- `YumiNail.sql` 与 MessageHub 初始化 SQL 暂未同步去掉所有 `AUTO_INCREMENT`。
|
||||
- 原因:
|
||||
- 目前应用层已经统一由 MyBatis-Plus 雪花生成器写入主键,运行时不会再依赖数据库自增。
|
||||
- 现有初始化 SQL 中存在多处不显式写入 `id` 的种子数据;如果直接移除自增定义,会导致空库初始化失败。
|
||||
- 现阶段兼容策略:
|
||||
- 运行时主键全部走雪花。
|
||||
- 初始化 SQL 继续保持可执行。
|
||||
- 如果后续要把初始化 SQL 也完全切到“显式雪花主键”,需要连同种子数据 ID 一并重排后再整体落地。
|
||||
|
||||
## 影响文件
|
||||
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/config/MyBatisPlusConfig.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/entity/MessageChannelConfigDO.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/entity/MessageDO.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/entity/MessageSourceSystemChannelDO.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/entity/MessageSourceSystemDO.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushTemplateDO.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/service/channel/sms/MockSmsChannelProvider.java`
|
||||
- `MessageHub/src/main/java/com/xiaowang/messagehub/support/id/TimeOrderedSnowflakeIdGenerator.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyBatisPlusConfig.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ObjectStorageFileController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceChangeDetailDO.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BaseEntity.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CouponServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubClientServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MinioServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/id/TimeOrderedSnowflakeIdGenerator.java`
|
||||
|
||||
## 验证结果
|
||||
|
||||
- 执行 `mvn -q -DskipTests compile`
|
||||
- `E:\code\xiaowang\YumiNail-Core` 编译通过
|
||||
- `E:\code\xiaowang\MessageHub` 编译通过
|
||||
|
||||
## 后续建议
|
||||
|
||||
- 如果后面要继续推进“初始化库也全部显式雪花 ID”,建议单独做一轮 SQL 种子重排,不要和业务功能改动混在一起,避免空库初始化链路被破坏。
|
||||
Reference in New Issue
Block a user