---
title: "分布式全局不重复ID生成算法"
author: "polim"
date: "2014-01-17T15:20:06Z"
tags: []
categories: ["互联网"]
slug: "id"
draft: false
lastmod: "2014-01-17T15:20:06Z"
id: 2005680
url: "https://polim.iteye.com/blog/2005680"
---

在分布式系统中经常会使用到生成全局唯一不重复ID的情况。本篇博客介绍生成的一些方法。

**常见的一些方式：**

1、通过DB做全局自增操作
优点：简单、高效
缺点：大并发、分布式情况下性能比较低

有些同学可能会说分库、分表的策略去降低DB的瓶颈，单要做到全局不重复需要提前按照一定的区域进行划分。例如：1~10000、10001~20000 等等。但这个灵活度比较低。

针对一些并发比较低的情况也可以使用类似这种方式。但大并发时不建议使用，DB很容易成为瓶颈。

2、获取当前时间纳秒或毫秒数
这种方式需要考虑的是在分布式集群中如果保证唯一性。

3、类似UUID的生成方式
生成的串比较大

//------------------------------------------------------------
综合上述情况我们需要一种在高并发、分布式系统中提供高效生成不重复唯一的一个ID，但要求生成的结果要小
方法1：
private static long INFOID_FLAG = 1260000000000L;
protected static int SERVER_ID = 1;

public synchronized long nextId() throws Exception {
    if(SERVER_ID <= 0)
        throw new Exception("server id is error,please check config file!");
    long infoid = System.currentTimeMillis() - INFOID_FLAG;
    infoid=(infoid<<7)| SERVER_ID;
    Thread.sleep(1);
    return infoid;
}

说明:
SERVER_ID为不同的服务器使用的不同server ID，如果不同的机器使用相同的server ID有可能会生成重复的全局ID

简单的应用在一定的并发情况下使用这种方式已经足够了，简单、高效。但是每秒生成的ID是有限的，因为Thread.sleep(1)会无形中带来一些时间的消耗。

方法2：


/**
 * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
 * @author Polim
 */
public class IdWorker {
	private final static long twepoch = 1288834974657L;
	// 机器标识位数
	private final static long workerIdBits = 5L;
	// 数据中心标识位数
	private final static long datacenterIdBits = 5L;
	// 机器ID最大值
	private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
	// 数据中心ID最大值
	private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
	// 毫秒内自增位
	private final static long sequenceBits = 12L;
	// 机器ID偏左移12位
	private final static long workerIdShift = sequenceBits;
	// 数据中心ID左移17位
	private final static long datacenterIdShift = sequenceBits + workerIdBits;
	// 时间毫秒左移22位
	private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

	private final static long sequenceMask = -1L ^ (-1L << sequenceBits);

	private static long lastTimestamp = -1L;

	private long sequence = 0L;
	private final long workerId;
	private final long datacenterId;

	public IdWorker(long workerId, long datacenterId) {
		if (workerId > maxWorkerId || workerId < 0) {
			throw new IllegalArgumentException("worker Id can't be greater than %d or less than 0");
		}
		if (datacenterId > maxDatacenterId || datacenterId < 0) {
			throw new IllegalArgumentException("datacenter Id can't be greater than %d or less than 0");
		}
		this.workerId = workerId;
		this.datacenterId = datacenterId;
	}

	public synchronized long nextId() {
		long timestamp = timeGen();
		if (timestamp < lastTimestamp) {
			try {
				throw new Exception("Clock moved backwards.  Refusing to generate id for "+ (lastTimestamp - timestamp) + " milliseconds");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (lastTimestamp == timestamp) {
			// 当前毫秒内，则+1
			sequence = (sequence + 1) & sequenceMask;
			if (sequence == 0) {
				// 当前毫秒内计数满了，则等待下一秒
				timestamp = tilNextMillis(lastTimestamp);
			}
		} else {
			sequence = 0;
		}
		lastTimestamp = timestamp;
		// ID偏移组合生成最终的ID，并返回ID
		long nextId = ((timestamp - twepoch) << timestampLeftShift)
				| (datacenterId << datacenterIdShift)
				| (workerId << workerIdShift) | 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();
	}
}

这种方式是一种比较高效的方式。也是twitter使用的一种方式。

测试类:----------------------------------------------------------
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class IdWorkerTest {
    public static void main(String args){
        IdWorkerTest test = new IdWorkerTest();
        test.test2();
    }
	
    public void test2(){
        final IdWorker w = new IdWorker(1,2);
        final CyclicBarrier cdl = new CyclicBarrier(100);
		
        for(int i = 0; i < 100; i++){
            new Thread(new Runnable() {
                @Override 
                public void run() {
                try {
                    cdl.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(w.nextId());}
             }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
           e.printStackTrace();
        }
		
    }
}