分布式ID生成方案

编程

1. 场景

大型分布式中涉及到:订单号、商品ID等。

分布式唯一ID有哪些特性或要求呢?

① 唯一性:生成的ID全局唯一,在特定范围内冲突概率极小。

② 有序性:生成的ID按某种规则有序,便于数据库插入及排序。

③ 可用性:可保证高并发下的可用性, 确保任何时候都能正确的生成ID。

④ 自主性:分布式环境下不依赖中心认证即可自行生成ID。

⑤ 安全性:不暴露系统和业务的信息, 如:订单数,用户数等

2. 解决方案

常见的有三种:UUID、数据库自增ID 、snowflake雪花算法。

参考https://blog.csdn.net/liudao51/article/details/103007892

public class SnowFlakeGenerator {

private final static String MSG_UID_PARSE = "{"UID":"%s","timestamp":"%s","workerId":"%d","dataCenterId":"%d","sequence":"%d"}";

private final static String DATE_PATTERN_DEFAULT = "yyyy-MM-dd HH:mm:ss.SSS";

private static String AT = "@";

/**

* 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)

*/

private final long twepoch = 1288834974657L;

/**

* 机器标识位数

*/

private final long workerIdBits = 5L;

private final long datacenterIdBits = 5L;

private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

/**

* 毫秒内自增位

*/

private final long sequenceBits = 12L;

private final long workerIdShift = sequenceBits;

private final long datacenterIdShift = sequenceBits + workerIdBits;

/**

* 时间戳左移动位

*/

private final long timestampLeftShift = sequenceBits + workerIdBits

+ datacenterIdBits;

private final long sequenceMask = -1L ^ (-1L << sequenceBits);

private final long workerId;

/**

* 数据标识 ID 部分

*/

private final long datacenterId;

/**

* 并发控制

*/

private long sequence = 0L;

/**

* 上次生产 ID 时间戳

*/

private long lastTimestamp = -1L;

/**

* 时间回拨最长时间(ms),超过这个时间就抛出异常

*/

private long timestampOffset = 5L;

public SnowFlakeGenerator() {

this.datacenterId = getDatacenterId(maxDatacenterId);

this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);

System.out.println("datacenterId =" + datacenterId + ",workerId ="

+ workerId);

}

/**

* <p>

* 有参构造器

* </p>

*

* @param workerId

* 工作机器 ID

* @param datacenterId

* 序列号

*/

public SnowFlakeGenerator(long workerId, long datacenterId) {

if (workerId > maxWorkerId || workerId < 0) {

throw new IllegalArgumentException(String.format(

"worker Id can"t be greater than %d or less than 0",

maxWorkerId));

}

if (datacenterId > maxDatacenterId || datacenterId < 0) {

throw new IllegalArgumentException(String.format(

"datacenter Id can"t be greater than %d or less than 0",

maxDatacenterId));

}

this.workerId = workerId;

this.datacenterId = datacenterId;

}

/**

* <p>

* 获取 maxWorkerId

* </p>

*/

protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {

StringBuilder mpid = new StringBuilder();

mpid.append(datacenterId);

String name = ManagementFactory.getRuntimeMXBean().getName();

System.out.println(name);

if (name != null && !"".equals(name)) {

/*

* GET jvmPid

*/

mpid.append(name.split(AT)[0]);

}

/*

* MAC + PID 的 hashcode 获取16个低位

*/

return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);

}

/**

* <p>

* 数据标识id部分

* </p>

*/

protected static long getDatacenterId(long maxDatacenterId) {

long id = 0L;

try {

InetAddress ip = InetAddress.getLocalHost();

NetworkInterface network = NetworkInterface.getByInetAddress(ip);

if (network == null) {

id = 1L;

} else {

byte[] mac = network.getHardwareAddress();

if (null != mac) {

id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;

id = id % (maxDatacenterId + 1);

}

}

} catch (Exception e) {

// log.warn(" getDatacenterId: " + e.getMessage());

}

return id;

}

/**

* 获取下一个ID

*

* @return

*/

public synchronized long nextId() {

long timestamp = timeGen();

// 闰秒

if (timestamp < lastTimestamp) {

long offset = lastTimestamp - timestamp;

if (offset <= timestampOffset) {

try {

wait(offset << 1);

timestamp = timeGen();

if (timestamp < lastTimestamp) {

throw new RuntimeException(

String.format(

"Clock moved backwards. Refusing to generate id for %d milliseconds",

offset));

}

} catch (Exception e) {

throw new RuntimeException(e);

}

} else {

throw new RuntimeException(

String.format(

"Clock moved backwards. Refusing to generate id for %d milliseconds",

offset));

}

}

if (lastTimestamp == timestamp) {

// 相同毫秒内,序列号自增

sequence = (sequence + 1) & sequenceMask;

if (sequence == 0) {

// 同一毫秒的序列数已经达到最大

timestamp = tilNextMillis(lastTimestamp);

}

} else {

// 不同毫秒内,序列号置为 1 - 3 随机数

//sequence = ThreadLocalRandom.current().nextLong(1, 3);

// 时间戳改变,毫秒内序列重置

sequence = 0L;

}

lastTimestamp = timestamp;

// 时间戳部分 | 数据中心部分 | 机器标识部分 | 序列号部分

return ((timestamp - twepoch) << timestampLeftShift)

| (datacenterId << datacenterIdShift)

| (workerId << workerIdShift) | sequence;

}

protected long tilNextMillis(long lastTimestamp) {

long timestamp = timeGen();

while (timestamp <= lastTimestamp) {

timestamp = timeGen();

}

return timestamp;

}

protected long timeGen() {

return System.currentTimeMillis();

}

public String parseId(Long uid) {

long totalBits = 64L;// 总位数

long signBits = 1L;// 标识

long timestampBits = 41L;// 时间戳

// 解析Uid:标识 -- 时间戳 -- 数据中心 -- 机器码 --序列

long sequence = (uid << (totalBits - sequenceBits)) >>> (totalBits - sequenceBits);

long dataCenterId = (uid << (timestampBits + signBits)) >>> (totalBits - datacenterIdBits);

long workerId = (uid << (timestampBits + signBits + datacenterIdBits)) >>> (totalBits - workerIdBits);

long deltaSeconds = uid >>> (datacenterIdBits + workerIdBits + sequenceBits);

// 时间处理(补上开始时间戳)

Date thatTime = new Date(twepoch + deltaSeconds);

String date = new SimpleDateFormat(DATE_PATTERN_DEFAULT)

.format(thatTime);

// 格式化输出

return String.format(MSG_UID_PARSE, uid, date, workerId, dataCenterId,

sequence);

}

/**

* 测试

*/

public static void main(String[] args) {

SnowFlakeGenerator s = new SnowFlakeGenerator();

for (int i = 0; i < 200; i++) {

long id = s.nextId();

System.out.println(Long.toBinaryString(id));

System.out.println(id);

System.out.println(s.parseId(id));

}

}

}

public class UuidGenerator {

/**

* 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.

*/

public static String uuid() {

return UUID.randomUUID().toString().replaceAll("-", "");

}

/**

* @param args

*/

public static void main(String[] args) {

System.out.println(UuidGenerator.uuid());

}

}

public class IdGeneratorUtils {

private static SnowFlakeGenerator s = new SnowFlakeGenerator();

/**

* 生成新ID

*

* 根据部署机器及生成器标识进行id生成 区别于用户标识分片,此方法用生成的 机器信息进行区分

*

* @return 新ID

*/

public static long genIdBySnowFlake() {

return s.nextId();

}

/**

* 解析ID

*

* @param id

* @return

*/

public static String parseSnowFlakeId(long id) {

return s.parseId(id);

}

/**

* 获取uuid

*

* @return uuid

*/

public static String genIdByUUID() {

return UuidGenerator.uuid();

}

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

long id = IdGeneratorUtils.genIdBySnowFlake();

System.out.println(IdGeneratorUtils.parseSnowFlakeId(id));

System.out.println(id);

System.out.println(IdGeneratorUtils.genIdByUUID());

}

}

}

 

以上是 分布式ID生成方案 的全部内容, 来源链接: utcz.com/z/516261.html

回到顶部