数据库知识点

全局唯一ID生成策略

2017-08-04  本文已影响0人  天下无敌强

Entrance

要求

twitter

Entrance

代码示例

public class IdWorker {

private final long workerId;
private final static long twepoch = 1288834974657L;
private long sequence = 0L;
private final static long workerIdBits = 4L;
public final static long maxWorkerId = -1L ^ -1L << workerIdBits;
private final static long sequenceBits = 10L;
private final static long workerIdShift = sequenceBits;
private final static long timestampLeftShift = sequenceBits + workerIdBits;
public final static long sequenceMask = -1L ^ -1L << sequenceBits;
private long lastTimestamp = -1L;

public IdWorker(final long workerId) {
    super();
    if (workerId > this.maxWorkerId || workerId < 0) {
        throw new IllegalArgumentException(
                String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId));
    }
    this.workerId = workerId;
}

public synchronized long nextId() {
    long timestamp = this.timeGen();
    if (this.lastTimestamp == timestamp) {
        this.sequence = (this.sequence + 1) & this.sequenceMask;
        if (this.sequence == 0) {
            System.out.println("###########" + sequenceMask);
            timestamp = this.tilNextMillis(this.lastTimestamp);
        }
    } else {
        this.sequence = 0;
    }
    if (timestamp < this.lastTimestamp) {
        try {
            throw new Exception(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
                    this.lastTimestamp - timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    this.lastTimestamp = timestamp;
    long nextId = ((timestamp - twepoch << timestampLeftShift)) | (this.workerId << this.workerIdShift)
            | (this.sequence);
    System.out.println("timestamp:" + timestamp + ",timestampLeftShift:" + timestampLeftShift + ",nextId:" + nextId
            + ",workerId:" + workerId + ",sequence:" + sequence);
    return nextId;
}

private long tilNextMillis(final long lastTimestamp) {
    long timestamp = this.timeGen();
    while (timestamp <= lastTimestamp) {
        timestamp = this.timeGen();
    }
    return timestamp;
}

private long timeGen() {
    return System.currentTimeMillis();
}

public static void main(String[] args) {
    IdWorker worker2 = new IdWorker(2);
    System.out.println(worker2.nextId());
}

}        

来自Flicker的解决方案

CREATE TABLE Tickets64 (
id bigint(20) unsigned NOT NULL auto_increment,
stub char(1) NOT NULL default '',
PRIMARY KEY (id),
UNIQUE KEY stub (stub)
) ENGINE=MyISAM

cluster

+-------------------+------+
| id | stub |
+-------------------+------+
| 72157623227190423 | a |
+-------------------+------+

cluster

REPLACE INTO Tickets64 (stub) VALUES ('a');
SELECT LAST_INSERT_ID();

cluster

TicketServer1:
auto-increment-increment = 2
auto-increment-offset = 1
 
TicketServer2:
auto-increment-increment = 2
auto-increment-offset = 2

UUID

优点

  1. 本地生成ID,不需要进行远程调用,时延低
  2. 扩展性好,基本可以认为没有性能上限

缺点

  1. 无法保证趋势递增
  2. uuid过长,往往用字符串表示,作为主键建立索引查询效率低,常见优化方案为“转化为两个uint64整数存储”或者“折半存储”(折半后不能保证唯一性)

基于redis的分布式ID生成器

entrance

redis的EVAL,EVALSHA命令的原理是利用redis的lua脚本执行功能,在每个节点上通过lua脚本生成唯一ID

关于生成的ID##

举例

cluster

MongoDB文档(Document)全局唯一ID

生成方式

|0|1|2|3|4|5|6 |7|8|9|10|11|
|时间戳 |机器ID|PID|计数器 |

cluster

总结

上一篇下一篇

猜你喜欢

热点阅读