生成唯一id写法,雪花算法

摘要:
这个工具直接调用就可以了,用法和写法如下:代码:这个是雪花算法的写法:1publicclassSnowFlakeUtil{23/**4*起始的时间戳5*/6privatefinalstaticlongSTART_STMP=1480166465631L;78/**9*每一部分占用的位数10*/11privatefinalstaticlongSEQUENCE_BIT=12;//序列号占用的位数12pr

这个工具直接调用就可以了,用法和写法如下:

代码:

这个是雪花算法的写法:

1 public classSnowFlakeUtil {
2 
3     /**
4 * 起始的时间戳
5      */
6     private final static long START_STMP = 1480166465631L;
7 
8     /**
9 * 每一部分占用的位数
10      */
11     private final static long SEQUENCE_BIT = 12; //序列号占用的位数
12     private final static long MACHINE_BIT = 5;  //机器标识占用的位数
13     private final static long DATACENTER_BIT = 5;//数据中心占用的位数
14 
15     /**
16 * 每一部分的最大值
17      */
18     private final static long MAX_DATACENTER_NUM = -1L ^ (-1L <<DATACENTER_BIT);
19     private final static long MAX_MACHINE_NUM = -1L ^ (-1L <<MACHINE_BIT);
20     private final static long MAX_SEQUENCE = -1L ^ (-1L <<SEQUENCE_BIT);
21 
22     /**
23 * 每一部分向左的位移
24      */
25     private final static long MACHINE_LEFT =SEQUENCE_BIT;
26     private final static long DATACENTER_LEFT = SEQUENCE_BIT +MACHINE_BIT;
27     private final static long TIMESTMP_LEFT = DATACENTER_LEFT +DATACENTER_BIT;
28 
29     private long datacenterId;  //数据中心
30     private long machineId;    //机器标识
31     private long sequence = 0L; //序列号
32     private long lastStmp = -1L;//上一次时间戳
33 
34     public SnowFlakeUtil(long datacenterId, longmachineId) {
35         if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
36             throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
37 }
38         if (machineId > MAX_MACHINE_NUM || machineId < 0) {
39             throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
40 }
41         this.datacenterId =datacenterId;
42         this.machineId =machineId;
43 }
44 
45     /**
46 * 产生下一个ID
47 *
48 * @return
49      */
50     public synchronized longnextId() {
51         long currStmp =getNewstmp();
52         if (currStmp <lastStmp) {
53             throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
54 }
55 
56         if (currStmp ==lastStmp) {
57             //相同毫秒内,序列号自增
58             sequence = (sequence + 1) &MAX_SEQUENCE;
59             //同一毫秒的序列数已经达到最大
60             if (sequence == 0L) {
61                 currStmp =getNextMill();
62 }
63         } else{
64             //不同毫秒内,序列号置为0
65             sequence = 0L;
66 }
67 
68         lastStmp =currStmp;
69 
70         return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
71                 | datacenterId << DATACENTER_LEFT      //数据中心部分
72                 | machineId << MACHINE_LEFT            //机器标识部分
73                 | sequence;                            //序列号部分
74 }
75 
76     private longgetNextMill() {
77         long mill =getNewstmp();
78         while (mill <=lastStmp) {
79             mill =getNewstmp();
80 }
81         returnmill;
82 }
83 
84     private longgetNewstmp() {
85         returnSystem.currentTimeMillis();
86 }
87 //小测试代码:
88 
89 //public static void main(String[] args) {
90 //SnowFlakeUtil snowFlake = new SnowFlakeUtil(2, 3);
91 //
92 //System.out.println(snowFlake.nextId());
93 //
94 //}
95 }

具体的调用:

1 importjava.text.SimpleDateFormat;
2 importjava.util.Date;
3 importjava.util.Random;
4 
5 public classCreateAUniqueIDUtil {
6     publicString ImageID(String subtype) {
7         SnowFlakeUtil snowFlake = new SnowFlakeUtil(2, 3);//调用雪花算法生成18位唯一id
8         long randomNumber18 = snowFlake.nextId();//18位唯一id
9         Random rand = new Random();//生成随机数
10         String cardNnumer = "";
11         for (int a = 0; a < 2; a++) {
12             cardNnumer += rand.nextInt(10);//生成2位随机数
13 }
14 //String subtype = "01";//01代表的是对应应用中解析时的参数,当前01代表 人员
15         String randomNumberString = "";
16         for (int a = 0; a < 5; a++) {
17             randomNumberString += rand.nextInt(10);//生成5位数字
18 }
19         Date date = newDate();
20         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
21         String format =df.format(date);
22         String ImageID = randomNumber18 + cardNnumer + subtype + format +randomNumberString;
23         returnImageID;
24 }
25 
26     publicString PersonID(String subtype) {
27         SnowFlakeUtil snowFlake = new SnowFlakeUtil(2, 3);//调用雪花算法生成18位唯一id
28         long randomNumber18 = snowFlake.nextId();//18位唯一id
29         Random rand = new Random();//生成随机数
30         String cardNnumer = "";
31         for (int i = 0; i < 23; i++) {
32             cardNnumer += rand.nextInt(10);//生成23位随机数
33 }
34 //String subtype = "01";//01-人员
35         String randomNumberString = "";
36         for (int a = 0; a < 5; a++) {
37             randomNumberString += rand.nextInt(10);//生成5位数字
38 }
39         String PersonID = randomNumber18 + cardNnumer + subtype +randomNumberString;
40         returnPersonID;
41 }
42 
43     publicString SourceID(String subtype) {
44         SnowFlakeUtil snowFlake = new SnowFlakeUtil(2, 3);//调用雪花算法生成18位唯一id
45         long randomNumber18 = snowFlake.nextId();//18位唯一id
46         Random rand = new Random();//生成随机数
47         String cardNnumer = "";
48         for (int i = 0; i < 2; i++) {
49             cardNnumer += rand.nextInt(10);//生成2位随机数
50 }
51 //String subtype = "02";//01-人员02-机动车03-非机动车04-物品05-场景06-人脸等
52         Date date = newDate();
53         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
54         String format =df.format(date);
55         String randomNumberString = "";
56         for (int a = 0; a < 5; a++) {
57             randomNumberString += rand.nextInt(10);//生成5位数字
58 }
59         String SourceID = randomNumber18 + cardNnumer + subtype + format +randomNumberString;
60         returnSourceID;
61 }
62 }

免责声明:文章转载自《生成唯一id写法,雪花算法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Hello World 之 CGALWeb serviser请求通道在等待 00:00:59.6479648 以后答复时超时。增加传递给请求调用的超时值,或者增加绑定上的 SendTimeout 值。分配给此操作的时间可能是更长超时的一部分。下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Android中关于日期时间与时区的使用总结

原文引自:http://www.2cto.com/kf/201312/266908.html 在开发Android的过程中,出现过几次由于日期时间导致的问题,而且主要是由于时区的原因导致,所以一直想总结一下,形成一个良好的开发规范。 一、Unix时间戳 Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、POSIX时间(...

seata no available service 'null' found, please make sure registry config correct

最近学习seata的时候报了错误no available service 'null' found, please make sure registry config correct,服务名在配置文件中都有的,没办法只能跟源码了 环境springcloudHoxton.SR3+Springboot2.2.5.RELEASE+seata1.1+nacos1....

Java如何正确的将数值转化为ArrayList?

Java中使用工具类Arrays.asList()看似可以把一个数组转为List,但实际使用时有两个坑:1、它是泛型方法,传入的参数必须是对象数组,当传入一个原生数据类型数组时,Arrays.asList() 的真正得到的参数就不是数组中的元素,而是数组对象本身。比如传入int[] intArray={1,2,3},它返回的list只有一个元素就是int...

C#的post请求 捕获错误代码的内容

public string Query(stringqueryString) { try{ HttpWebRequest request =(HttpWebRequest)HttpWebRequest.Create(AOPResource.LVSRequestURL);...

C#实现JSON序列化与反序列化

JSON(JavaScript Object Notation)——JavaScript对象表示法,是JavaScript用来处理数据的一种格式,大部分是用来处理JavaScript和web服务器端之间的数据交换,把后台web服务器的数据传递到前台,然后使用JavaScript进行处理,例如ajax等,是独立于语言和平台的轻量级的数据交换格式。 JSO...

【一】、.net core 3.1 创建windows服务并集成Serilog的步骤记录

1、新建项目   选择“Worker Service”,如下图: 2、添加nuget引用   Microsoft.Extensions.Hosting.WindowsServices   Serilog.Extensions.Hosting   Serilog.Sinks.Console   Serilog.Sinks.File 3、修改Program的...