问题起因
k8s 部署的一个服务的两个节点集群 最近频繁报错,数据库主键ID重复,导致数据插入报错
 
问题定位
还在定位。。。。
问题解决
解决办法主要有两个
- 指定mybatis-plus workerId dataCenterId 全局配置
#注意这里使用的随机策略  随机区间  1-31
mybatis-plus.global-config.worker-id=${random.int(1,31)}
mybatis-plus.global-config.datacenter-id=${random.int(1,31)}
此方法优点 可能很小的概率重复
 此方法缺点 当部署节点服务过多时 重复概率会提高
2.使用开源项目 https://github.com/imadcn/idworker
 workerId 和 dataCenterId 生成 使用zk生成
 使用方式 mybatis-plus 版本大于3.4 可直接使用bean注册
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.ImadcnIdentifierGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author leon
 * @date 2023-01-16 09:45:39
 */
@Configuration
public class IdGeneratorConfig {
    
    @Bean
    public IdentifierGenerator identifierGenerator() {
        //可配置单个 或者多个节点  多个节点用,分割
        return new ImadcnIdentifierGenerator("localhost:2181");
    }
    
}
如果mybatis-plus版本低于 3.4 需要自行引入 依赖
<!-- 最新的版本 如下 -->
<dependency>
    <groupId>com.imadcn.framework</groupId>
    <artifactId>idworker</artifactId>
    <version>1.5.0</version>
</dependency>
需要自行包装 使用 idworker中的类 来实现 IdentifierGenerator 接口 后续仍是注入的方式 如上
兼容性 需要自行测试
 此方式优点 workerId 和 dataCenterId 依靠zk生成 基本不会重复
 此方式缺点 能够支持节点有限 最大为1024个(绝大数场景够用了)
 需要自行部署 zk



















