解决集群下mp的雪花id重复问题

发布时间 2023-10-31 15:20:13作者: 佳沃

雪花算法的核心能影响到id生成的几个因素:

  1. 服务器时间
  2. workId(机器 ID 部分)
  3. datacenterId(数据标识 ID 部分)

根据源码

public void init(GlobalConfig globalConfig) {
    // 初始化 Sequence
//这里需要同时设置workerId和datacenterId
    if (null != globalConfig.getWorkerId()
        && null != globalConfig.getDatacenterId()) {
        IdWorker.initSequence(globalConfig.getWorkerId(), globalConfig.getDatacenterId());
    }
    // 打印 Banner
    if (globalConfig.isBanner()) {
        System.out.println(" _ _   |_  _ _|_. ___ _ |    _ ");
        System.out.println("| | |\\/|_)(_| | |_\\  |_)||_|_\\ ");
        System.out.println("     /               |         ");
        System.out.println("                        "+MybatisPlusVersion.getVersion()+" ");
    }
}

发现workerId和datacenterId必须同时设置才会获取我们设置的值。

# 设置随机
mybatis-plus.global-config.worker-id: ${random.int(1,31)}
mybatis-plus.global-config.datacenter-id: ${random.int(1,31)}