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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import com.sankuai.inf.leaf.common.Utils;
import com.sankuai.inf.leaf.snowflake.exception.OverMaxTimeStampException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -20,11 +21,13 @@ public boolean init() {
private static final Logger LOGGER = LoggerFactory.getLogger(SnowflakeIDGenImpl.class);

private final long twepoch;
private final long timeStampBits = 41L;
private final long workerIdBits = 10L;
private final long maxWorkerId = ~(-1L << workerIdBits);//最大能够分配的workerid =1023
private final long sequenceBits = 12L;
private final long workerIdShift = sequenceBits;
private final long timestampLeftShift = sequenceBits + workerIdBits;
private final long maxTimeStamp;
private final long sequenceMask = ~(-1L << sequenceBits);
private long workerId;
private long sequence = 0L;
Expand All @@ -43,6 +46,7 @@ public SnowflakeIDGenImpl(String zkAddress, int port) {
*/
public SnowflakeIDGenImpl(String zkAddress, int port, long twepoch) {
this.twepoch = twepoch;
this.maxTimeStamp = ~(-1L << timeStampBits) + twepoch;
Preconditions.checkArgument(timeGen() > twepoch, "Snowflake not support twepoch gt currentTime");
final String ip = Utils.getIp();
SnowflakeZookeeperHolder holder = new SnowflakeZookeeperHolder(ip, String.valueOf(port), zkAddress);
Expand All @@ -60,6 +64,9 @@ public SnowflakeIDGenImpl(String zkAddress, int port, long twepoch) {
@Override
public synchronized Result get(String key) {
long timestamp = timeGen();
if (timestamp>maxTimeStamp) {
throw new OverMaxTimeStampException("current timestamp is over maxTimeStamp, the generate id will be negative");
}
if (timestamp < lastTimestamp) {
long offset = lastTimestamp - timestamp;
if (offset <= 5) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.sankuai.inf.leaf.snowflake.exception;

public class OverMaxTimeStampException extends RuntimeException {
public OverMaxTimeStampException(String msg){
super(msg);
}
}