Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复时间差过大,超过41位溢出,导致生成的id负数的问题 #105

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

NotFound9
Copy link

@NotFound9 NotFound9 commented May 4, 2020

因为Leaf框架是沿用snowflake的位数分配,
image

最大41位时间差+10位的workID+12位序列化,但是由于snowflake是强制要求第一位为符号位0,否则生成的id转换为十进制后会是复试,但是Leaf项目中没有对时间差进行校验,当时间戳过大或者自定义的twepoch设置不当过小,会导致计算得到的时间差过大,转化为2进制后超过41位,且第一位为1,会导致生成的long类型的id为负数,例如当timestamp = twepoch+2199023255552L时,
此时在生成id时,timestamp - twepoch会等于2199023255552,2199023255552转换为二进制后是1+41个0,此时生成的id由于符号位是1,id会是负数-9223372036854775793

 long id = ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;

虽然这是很特殊的一种情况,但是我看百度uid-genertor也考虑到了这种情况,代码中有对这种情况的判断,所以我觉得还是Leaf也有必要修复一下,所以我提了这个PR,对这个问题进行了修复,希望美团的朋友们有空可以看一看。

另外美团对于Leaf的介绍文章里面对于snowflake算法介绍用的配图存在错误,序列号的位数分配应该是12位,而不是10位,不然总位数不是63位。
image

@NotFound9 NotFound9 changed the title 修复时间差过大,导致生成的id 修复时间差过大溢出,导致生成的id负数的问题 May 4, 2020
@NotFound9 NotFound9 changed the title 修复时间差过大溢出,导致生成的id负数的问题 修复时间差过大,超过41位溢出,导致生成的id负数的问题 May 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant