重构:统一核心和消息中心的雪花 ID

This commit is contained in:
xiaowang
2026-03-30 14:42:13 +08:00
parent 184e1ffe4b
commit f1b44d6630
21 changed files with 555 additions and 90 deletions
@@ -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();
}
};
}
}
@@ -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);
@@ -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);
@@ -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;
/**
@@ -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;
}
@@ -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);
@@ -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
@@ -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);
@@ -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);
}
@@ -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();
}
}