为什么需要分布式ID(分布式集群环境下的全局唯⼀ID)
image.png

1. UUID(可以⽤)

UUID 是指Universally Unique Identifier,翻译为中⽂是通⽤唯⼀识别码
产⽣重复 UUID 并造成错误的情况⾮常低,是故⼤可不必考虑此问题。
Java中得到⼀个UUID,可以使⽤java.util包提供的⽅法

  1. public class MyTest {
  2. public static void main(String[] args) {
  3. System.out.println(java.util.UUID.randomUUID().toString());
  4. }
  5. }

image.png

2. 独⽴数据库的⾃增ID

⽐如A表分表为A1表和A2表,那么肯定不能让A1表和A2表的ID⾃增,那么ID怎么获取呢?我们可以单独的创建⼀个Mysql数据库,在这个数据库中创建⼀张表,这张表的ID设置为⾃增,其他地⽅需要全局唯⼀ID的时候,就模拟向这个Mysql数据库的这张表中模拟插⼊⼀条记录,此时ID会⾃增,然后我们可以通过Mysql的select last_insert_id() 获取到刚刚这张表中⾃增⽣成的ID.
⽐如,我们创建了⼀个数据库实例global_id_generator,在其中创建了⼀个数据表,表结构如下:

-- ----------------------------
-- Table structure for DISTRIBUTE_ID
-- ----------------------------
DROP TABLE IF EXISTS `DISTRIBUTE_ID`;
CREATE TABLE `DISTRIBUTE_ID` (
  `id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `createtime` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

当分布式集群环境中哪个应⽤需要获取⼀个全局唯⼀的分布式ID的时候,就可以使⽤代码连接这个数据库实例,执⾏如下sql语句即可。

insert into DISTRIBUTE_ID(createtime) values(NOW());
select LAST_INSERT_ID();

注意:

  1. 这⾥的createtime字段⽆实际意义,是为了随便插⼊⼀条数据以⾄于能够⾃增id。
  2. 使⽤独⽴的Mysql实例⽣成分布式id,虽然可⾏,但是性能和可靠性都不够好,因为你需要代码连接到数据库才能获取到id,性能⽆法保障,另外mysql数据库实例挂掉了,那么就⽆法获取分布式id了。
  3. 有⼀些开发者⼜针对上述的情况将⽤于⽣成分布式id的mysql数据库设计成了⼀个集群架构,那么其实这种⽅式现在基本不⽤,因为过于麻烦了。

    3. SnowFlake 雪花算法(可以⽤,推荐)

    3.1 算法思想

    雪花算法是Twitter推出的⼀个⽤于⽣成分布式ID的策略。
    雪花算法是⼀个算法,基于这个算法可以⽣成ID,⽣成的ID是⼀个long型,那么在Java中⼀个long型是8个字节,算下来是64bit,如下是使⽤雪花算法⽣成的⼀个ID的⼆进制形式示意:
    image.png
    另外,⼀切互联⽹公司也基于上述的⽅案封装了⼀些分布式ID⽣成器,⽐如滴滴的tinyid(基于数据库实现)、百度的uidgenerator(基于SnowFlake)和美团的leaf(基于数据库和SnowFlake)等,他们在。

    3.2 Java实现的雪花算法(了解即可)

    ```java /**

    • 官方推出,Scala编程语言来实现的
    • Java前辈用Java语言实现了雪花算法 */ public class IdWorker{

      //下面两个每个5位,加起来就是10位的工作机器id private long workerId; //工作id private long datacenterId; //数据id //12位的序列号 private long sequence;

      public IdWorker(long workerId, long datacenterId, long sequence){ // sanity check for workerId 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));
      

      } System.out.printf(“worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d”,

             timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);
      

      this.workerId = workerId; this.datacenterId = datacenterId; this.sequence = sequence; }

      //初始时间戳 private long twepoch = 1288834974657L;

      //长度为5位 private long workerIdBits = 5L; private long datacenterIdBits = 5L; //最大值 private long maxWorkerId = -1L ^ (-1L << workerIdBits); private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); //序列号id长度 private long sequenceBits = 12L; //序列号最大值 private long sequenceMask = -1L ^ (-1L << sequenceBits);

      //工作id需要左移的位数,12位 private long workerIdShift = sequenceBits; //数据id需要左移位数 12+5=17位 private long datacenterIdShift = sequenceBits + workerIdBits; //时间戳需要左移位数 12+5+5=22位 private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

      //上次时间戳,初始值为负数 private long lastTimestamp = -1L;

      public long getWorkerId(){ return workerId; }

      public long getDatacenterId(){ return datacenterId; }

      public long getTimestamp(){ return System.currentTimeMillis(); }

      //下一个ID生成算法 public synchronized long nextId() { long timestamp = timeGen();

      //获取当前时间戳如果小于上次时间戳,则表示时间戳获取出现异常 if (timestamp < lastTimestamp) {

         System.err.printf("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp);
         throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                 lastTimestamp - timestamp));
      

      }

      //获取当前时间戳如果等于上次时间戳 //说明:还处在同一毫秒内,则在序列号加1;否则序列号赋值为0,从0开始。 if (lastTimestamp == timestamp) { // 0 - 4095

         sequence = (sequence + 1) & sequenceMask;
         if (sequence == 0) {
             timestamp = tilNextMillis(lastTimestamp);
         }
      

      } else {

         sequence = 0;
      

      }

      //将上次时间戳值刷新 lastTimestamp = timestamp;

      /**

       * 返回结果:
       * (timestamp - twepoch) << timestampLeftShift) 表示将时间戳减去初始时间戳,再左移相应位数
       * (datacenterId << datacenterIdShift) 表示将数据id左移相应位数
       * (workerId << workerIdShift) 表示将工作id左移相应位数
       * | 是按位或运算符,例如:x | y,只有当x,y都为0的时候结果才为0,其它情况结果都为1。
       * 因为个部分只有相应位上的值有意义,其它位上都是0,所以将各部分的值进行 | 运算就能得到最终拼接好的id
      

      */ return ((timestamp - twepoch) << timestampLeftShift) |

             (datacenterId << datacenterIdShift) |
             (workerId << workerIdShift) |
             sequence;
      

      }

      //获取时间戳,并与上次时间戳比较 private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) {

         timestamp = timeGen();
      

      } return timestamp; }

      //获取系统时间戳 private long timeGen(){ return System.currentTimeMillis(); }

      public static void main(String[] args) { IdWorker worker = new IdWorker(21,10,0); for (int i = 0; i < 100; i++) {

         System.out.println(worker.nextId());
      

      } }

}

<a name="fGgoM"></a>
# 4. 借助Redis的Incr命令获取全局唯⼀ID(推荐)
<a name="Z4cge"></a>
## 4.1 思想
Redis Incr 命令将 key 中储存的数字值增⼀。如果 key 不存在,那么 key 的值会先被初始化为 0,然后再执⾏ INCR 操作。<br /><key,value><br /><id,><br />.incr(id) 1 2 3 4<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/21859640/1648053935606-887d37a7-590f-456c-b136-1d20e9aaf7aa.png#clientId=ua778a244-0af5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=844&id=uf1345ad1&margin=%5Bobject%20Object%5D&name=image.png&originHeight=844&originWidth=1314&originalType=binary&ratio=1&rotation=0&showTitle=false&size=95670&status=done&style=none&taskId=u5214ab9e-5a52-4381-9c18-25b9f8e5780&title=&width=1314)
<a name="HOn5B"></a>
## 4.2 Redis安装
(示意,我们这⾥安装单节点使⽤⼀下,具体Redis⾃身的内容在后续分布式缓存课程中详细讲解)

- 官⽹下载redis-3.2.10.tar.gz
- 上传到linux服务器解压 tar -zxvf redis-3.2.10.tar.gz
- cd 解压⽂件⽬录,对解压的redis进⾏编译

make

- 然后cd 进⼊src⽬录,执⾏make install
- 修改解压⽬录中的配置⽂件redis.conf,关掉保护模式

![image.png](https://cdn.nlark.com/yuque/0/2022/png/21859640/1648054031265-01a31c0d-18d8-401a-9308-167434133854.png#clientId=ua778a244-0af5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=444&id=u3ccbd6e9&margin=%5Bobject%20Object%5D&name=image.png&originHeight=444&originWidth=439&originalType=binary&ratio=1&rotation=0&showTitle=false&size=80470&status=done&style=none&taskId=u3f7490d6-ee81-4b5a-92f8-9c6339e1207&title=&width=439)

- 在src⽬录下执⾏ ./redis-server ../redis.conf 启动redis服务
<a name="Oz3Cm"></a>
## 4.3 ava代码中使⽤Jedis客户端调⽤Reids的incr命令获得⼀个全局的id
<a name="Me3fF"></a>
### 4.3.1 引⼊jedis客户端jar
```xml
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.9.0</version>
</dependency>

4.3.2 Java代码(此处我们就是连接单节点,也不使⽤连接池)

Jedis jedis = new Jedis("127.0.0.1",6379);
try {
    long id = jedis.incr("id");
    System.out.println("从redis中获取的分布式id为:" + id);
} finally {
    if (null != jedis) {
        jedis.close();
    }
}