Kaynağa Gözat

fix: ID生成器改为进程内单例,多实例支持配置 workerId

- IDGenerator.INS() 原实现每次 new 新实例(sequence/workerId 全 0),
  同一毫秒两次调用生成完全相同 ID 导致主键冲突
- INS() 改为返回静态单例;CustomIdGenerator 的 workerId/datacenterId
  支持 kym.id.worker-id / kym.id.datacenter-id 配置(默认0,兼容现有部署),
  多实例部署时配置不同值即可避免跨进程撞号

Co-Authored-By: Claude <noreply@anthropic.com>
skyline 3 hafta önce
ebeveyn
işleme
e731cd1a18

+ 10 - 5
car-wash-common/src/main/java/com/kym/common/config/CustomIdGenerator.java

@@ -2,6 +2,7 @@ package com.kym.common.config;
 
 import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
 import com.kym.common.utils.IDGenerator;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
 /**
@@ -12,15 +13,19 @@ import org.springframework.stereotype.Component;
 @Component
 public class CustomIdGenerator implements IdentifierGenerator {
 
-    private IDGenerator idGenerator;
+    private final IDGenerator idGenerator;
 
-    public CustomIdGenerator() {
-        this.idGenerator = new IDGenerator(0, 0);
+    /**
+     * workerId/datacenterId 支持配置(默认 0),多实例部署时通过
+     * kym.id.worker-id / kym.id.datacenter-id 区分,避免跨进程同毫秒撞号
+     */
+    public CustomIdGenerator(@Value("${kym.id.worker-id:0}") long workerId,
+                             @Value("${kym.id.datacenter-id:0}") long datacenterId) {
+        this.idGenerator = new IDGenerator(workerId, datacenterId);
     }
 
     @Override
     public Long nextId(Object entity) {
-        final long id = idGenerator.nextId();
-        return id;
+        return idGenerator.nextId();
     }
 }

+ 8 - 2
car-wash-common/src/main/java/com/kym/common/utils/IDGenerator.java

@@ -17,8 +17,14 @@ import org.springframework.stereotype.Component;
 @Component
 public class IDGenerator {
 
-    public static IDGenerator INS(){
-        return new IDGenerator();
+    /**
+     * 进程内单例:原实现每次 new 一个新实例(sequence/workerId 均从 0 开始),
+     * 同一毫秒内两次调用会生成完全相同的 ID,导致主键冲突
+     */
+    private static final IDGenerator INSTANCE = new IDGenerator(0, 0);
+
+    public static IDGenerator INS() {
+        return INSTANCE;
     }