简介: 分布式系统中最关键的一个问题,ID生成,本文,一篇带你掌握node
系统惟一ID是咱们在设计一个系统的时候经常会碰见的问题,也经常为这个问题而纠结。生成ID的方法有不少,适应不一样的场景、需求以及性能要求。因此有些比较复杂的系统会有多个ID生成的策略。下面就介绍一些常见的ID生成策略。git
优势:github
1)简单,代码方便,性能能够接受。算法
2)数字ID自然排序,对分页或者须要排序的结果颇有帮助。数据库
缺点:服务器
1)不一样数据库语法和实现不一样,数据库迁移的时候或多数据库版本支持的时候须要处理。并发
2)在单个数据库或读写分离或一主多从的状况下,只有一个主库能够生成。有单点故障的风险。less
3)在性能达不到要求的状况下,比较难于扩展。分布式
4)若是碰见多个系统须要合并或者涉及到数据迁移会至关痛苦。ide
5)分表分库的时候会有麻烦。
优化方案:
1)针对主库单点,若是有多个Master库,则每一个Master库设置的起始数字不同,步长同样,能够是Master的个数。好比:Master1 生成的是 1,4,7,10,Master2生成的是2,5,8,11 Master3生成的是 3,6,9,12。这样就能够有效生成集群中的惟一ID,也能够大大下降ID生成数据库操做的负载。
优势:
1)简单,代码方便。
2)生成ID性能很是好,基本不会有性能问题。
3)全球惟一,在碰见数据迁移,系统数据合并,或者数据库变动等状况下,能够从容应对。
缺点:
1)没有排序,没法保证趋势递增。
2)UUID每每是使用字符串存储,查询的效率比较低。
3)存储空间比较大,若是是海量数据库,就须要考虑存储量的问题。
4)传输数据量大
5)不可读。
///
/// 根据GUID获取惟一数字序列
///
public static long GuidToInt64()
{
byte[] bytes = Guid.NewGuid().ToByteArray(); return BitConverter.ToInt64(bytes, 0);
}
2)为了解决UUID无序的问题,NHibernate在其主键生成方式中提供了Comb算法(combined guid/timestamp)。保留GUID的10个字节,用另6个字节表示GUID生成的时间(DateTime)。
///
/// Generate a new using the comb algorithm.
///
private Guid GenerateComb()
{
byte[] guidArray = Guid.NewGuid().ToByteArray(); DateTime baseDate = new DateTime(1900, 1, 1); DateTime now = DateTime.Now; // Get the days and milliseconds which will be used to build //the byte string TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); TimeSpan msecs = now.TimeOfDay; // Convert to a byte array // Note that SQL Server is accurate to 1/300th of a // millisecond so we divide by 3.333333 byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds / 3.333333)); // Reverse the bytes to match SQL Servers ordering Array.Reverse(daysArray); Array.Reverse(msecsArray); // Copy the bytes into the guid Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); return new Guid(guidArray);
}
用上面的算法测试一下,获得以下的结果:做为比较,前面3个是使用COMB算法得出的结果,最后12个字符串是时间序(统一毫秒生成的3个UUID),过段时间若是再次生成,则12个字符串会比图示的要大。后面3个是直接生成的GUID。
若是想把时间序放在前面,能够生成后改变12个字符串的位置,也能够修改算法类的最后两个Array.Copy。
可使用Redis集群来获取更高的吞吐量。假如一个集群中有5台Redis。能够初始化每台Redis的值分别是1,2,3,4,5,而后步长都是5。各个Redis生成的ID为:
A:1,6,11,16,21
B:2,7,12,17,22
C:3,8,13,18,23
D:4,9,14,19,24
E:5,10,15,20,25
这个,随便负载到哪一个机肯定好,将来很难作修改。可是3-5台服务器基本可以知足器上,均可以得到不一样的ID。可是步长和初始值必定须要事先须要了。使用Redis集群也能够方式单点故障的问题。
另外,比较适合使用Redis来生成天天从0开始的流水号。好比订单号=日期+当日自增加号。能够天天在Redis中生成一个Key,使用INCR进行累加。
优势:
1)不依赖于数据库,灵活方便,且性能优于数据库。
2)数字ID自然排序,对分页或者须要排序的结果颇有帮助。
缺点:
1)若是系统中没有Redis,还须要引入新的组件,增长系统复杂度。
2)须要编码和配置的工做量比较大。
C#代码以下:
///
/// From: https://github.com/twitter/snowflake /// An object that generates IDs. /// This is broken into a separate class in case /// we ever want to support multiple worker threads /// per process /// </summary> public class IdWorker { private long workerId; private long datacenterId; private long sequence = 0L; private static long twepoch = 1288834974657L; private static long workerIdBits = 5L; private static long datacenterIdBits = 5L; private static long maxWorkerId = -1L ^ (-1L << (int)workerIdBits); private static long maxDatacenterId = -1L ^ (-1L << (int)datacenterIdBits); private static long sequenceBits = 12L; private long workerIdShift = sequenceBits; private long datacenterIdShift = sequenceBits + workerIdBits; private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private long sequenceMask = -1L ^ (-1L << (int)sequenceBits); private long lastTimestamp = -1L; private static object syncRoot = new object(); public IdWorker(long workerId, long datacenterId) { // sanity check for workerId if (workerId > maxWorkerId || workerId < 0) { throw new ArgumentException(string.Format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new ArgumentException(string.Format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; } public long nextId() { lock (syncRoot) { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new ApplicationException(string.Format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; return ((timestamp - twepoch) << (int)timestampLeftShift) | (datacenterId << (int)datacenterIdShift) | (workerId << (int)workerIdShift) | sequence; } } protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } protected long timeGen() { return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; } }
测试代码以下:
private static void TestIdWorker()
{ HashSet<long> set = new HashSet<long>(); IdWorker idWorker1 = new IdWorker(0, 0); IdWorker idWorker2 = new IdWorker(1, 0); Thread t1 = new Thread(() => DoTestIdWoker(idWorker1, set)); Thread t2 = new Thread(() => DoTestIdWoker(idWorker2, set)); t1.IsBackground = true; t2.IsBackground = true; t1.Start(); t2.Start(); try { Thread.Sleep(30000); t1.Abort(); t2.Abort(); } catch (Exception e) { } Console.WriteLine("done"); } private static void DoTestIdWoker(IdWorker idWorker, HashSet<long> set) { while (true) { long id = idWorker.nextId(); if (!set.Add(id)) { Console.WriteLine("duplicate:" + id); } Thread.Sleep(1); } }
snowflake算法能够根据自身项目的须要进行必定的修改。好比估算将来的数据中心个数,每一个数据中心的机器数以及统一毫秒能够能的并发数来调整在算法中所须要的bit数。
优势:
1)不依赖于数据库,灵活方便,且性能优于数据库。
2)ID按照时间在单机上是递增的。
缺点:
1)在单机上是递增的,可是因为涉及到分布式环境,每台机器上的时钟不可能彻底同步,也许有时候也会出现不是全局递增的状况。
其格式以下:
前4 个字节是从标准纪元开始的时间戳,单位为秒。时间戳,与随后的5 个字节组合起来,提供了秒级别的惟一性。因为时间戳在前,这意味着ObjectId 大体会按照插入的顺序排列。这对于某些方面颇有用,如将其做为索引提升效率。这4 个字节也隐含了文档建立的时间。绝大多数客户端类库都会公开一个方法从ObjectId 获取这个信息。接下来的3 字节是所在主机的惟一标识符。一般是机器主机名的散列值。这样就能够确保不一样主机生成不一样的ObjectId,不产生冲突。为了确保在同一台机器上并发的多个进程产生的ObjectId 是惟一的,接下来的两字节来自产生ObjectId 的进程标识符(PID)。前9 字节保证了同一秒钟不一样机器不一样进程产生的ObjectId 是惟一的。后3 字节就是一个自动增长的计数器,确保相同进程同一秒产生的ObjectId 也是不同的。同一秒钟最多容许每一个进程拥有2563(16 777 216)个不一样的ObjectId。
实现的源码能够到MongoDB官方网站下载。