我们生产中用的雪花算法代码如下:
1
2
3
4
5
6
7
8
9
10
11
|
@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
//从docker启动参数中获取应用实例WID环境变量
Long workId = (long) Math.random() * 31;
Long dataCenterId = (long) Math.random() * 31;
log.info("workId={},dataCenterId={}", workId, dataCenterId);
IdentifierGenerator identifierGenerator = new DefaultIdentifierGenerator(workId, dataCenterId);
return plusProperties -> plusProperties.getGlobalConfig().setIdentifierGenerator(identifierGenerator);
}
|
最近总是发现主键重复的问题,就很奇怪,我们目前就两个实例,为什么会发生重复了,后来同事调试后发现是我们的写法出问题了,如下写法最后生成的workId和dataCenterId永远为零:
1
2
3
4
|
Long workId = (long) Math.random() * 31;
Long dataCenterId = (long) Math.random() * 31;
|
正确的写法应该如下:
1
2
3
4
|
Long workId = (long) (Math.random() * 31);
Long dataCenterId = (long) (Math.random() * 31);
|
其实我目前还接受不了用随机数生成workId和dataCenterId,我觉得风险还是存在的,而且概率是未知的,有点浮沙筑高台的感觉,容易让人心慌。