雪花算法生成的id总共64位8个字节,结构如下:
符号位 | 时间位 | 工作机器标识位 | 序列位 |
1位(固定位0) | 41位 | 10位 | 12位 |
worker.id
sharding jdbc 4.1.1使用雪花算法生成分布式id时,会使用到属性work.id表示机器标识位,取值范围[0,1024),配置示例如下:
sharding:
tables:
user:
actual-data-nodes: ds$->{0..1}.user_$->{1..3}
key-generator:
column: id
type: SNOWFLAKE
props:
worker.id: 100
max.vibration.offset: 2
database-strategy:
inline:
sharding-column: id
algorithm-expression: ds$->{id%2}
table-strategy:
inline:
sharding-column: id
algorithm-expression: user_$->{id%3+1}
如果希望动态指定work.id属性,可以通过调用System.setProperty()的方式实现,示例如下:
package com.zhut.sharding.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
static {
System.setProperty("workerId", String.valueOf(100));
}
}
这里只是个例子,具体的值可以通过ip或者hostname经过一定的运算后得到。
修改配置文件,改成这样 worker.id: ${workerId}
max.vibration.offset
标准的雪花算法,在生成id时,如果本次生成id的时间与上一次生成id的时间不是同一毫秒,即跨了毫秒,则序列部分会从0开始计算。如果不是高并发环境下,每次生成id都可能跨毫秒,这样每次生成的id都是偶数,如果根据id进行奇偶分片,则数据全部落到偶数表里面了,这种结果肯定不是我们期望的。
我们期望的结果是,数据能均匀的分布到奇偶表中,那么跨毫秒生成的id的序列就不能一直从0开始。max.vibration.offset就能解决这个问题,先看看源码(SnowflakeShardingKeyGenerator,在eclipse中可以使用Ctrl+T进行搜索):
private int sequenceOffset = -1;
@Override
public synchronized Comparable<?> generateKey() {
long currentMilliseconds = timeService.getCurrentMillis();
if (waitTolerateTimeDifferenceIfNeed(currentMilliseconds)) {
currentMilliseconds = timeService.getCurrentMillis();
}
if (lastMilliseconds == currentMilliseconds) {
if (0L == (sequence = (sequence + 1) & SEQUENCE_MASK)) {
currentMilliseconds = waitUntilNextTime(currentMilliseconds);
}
} else {
vibrateSequenceOffset();
sequence = sequenceOffset;
}
lastMilliseconds = currentMilliseconds;
return ((currentMilliseconds - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (getWorkerId() << WORKER_ID_LEFT_SHIFT_BITS) | sequence;
}
private int getMaxVibrationOffset() {
int result = Integer.parseInt(properties.getProperty("max.vibration.offset", String.valueOf(DEFAULT_VIBRATION_VALUE)));
Preconditions.checkArgument(result >= 0 && result <= SEQUENCE_MASK, "Illegal max vibration offset");
return result;
}
private void vibrateSequenceOffset() {
sequenceOffset = sequenceOffset >= getMaxVibrationOffset() ? 0 : sequenceOffset + 1;
}
生成key时,如果跨毫秒了,则会执行vibrateSequenceOffset方法,该方法会读取max.vibration.offset的值,如果sequenceOffset大于或等于该值,则序列从0开始,否则序列每次在上次一次的基础上加1。则样就保证了奇偶均匀分布了。
如果max.vibration.offset配置为1,则每次的序列都按照0,1这个顺序反复取,如果配置位2,就按照0,1,2反复取。