我是靠谱客的博主 还单身项链,这篇文章主要介绍设计一个分布式的全局唯一ID生成器1、要求长度为8,现在分享给大家,希望可以做个参考。

1、要求长度为8

2、只能包含[a-zA-Z0-9]

3、必须唯一 思路

   1、定义一个静态数组chars包含a-zA-Z0-9,总共62个
   2、通过UUID.randomUUID().toString(),生成36位的uuid,生成的36位id带着4个‘-’字符,我们把字符‘-’去掉,剩下32个16进制的字符。

   3、我们要生成一个8位的id,因此我们把32个字符分成8组,每组4个,(算法的关键->)我们把每组4个字符看成一个整体,把他变成十进制的数字,之后取余,并把chars数组中应余数位置的字符添加到id中。

   4、引入MD5依赖,写加密算法 6、加密之后输出,下面上代码。

    id生成部分:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import org.junit.Test; ​ import java.util.UUID; ​ public class Createid {    public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",            "W", "X", "Y", "Z" };    public static String creatUUID(){        StringBuffer shortBuffer = new StringBuffer();        System.out.println("原来生成的36位uuid");        String uuid = UUID.randomUUID().toString();        System.out.println(uuid);        uuid=uuid.replace("-", "");        System.out.println("替换-后的32位uuid");        System.out.println(uuid);        for (int i = 0; i < 8; i++) {            String str = uuid.substring(i * 4, i * 4 + 4);            int x = Integer.parseInt(str, 16);            shortBuffer.append(chars[x % 62]);       }        return shortBuffer.toString();   }    @Test    public void test(){        String str=creatUUID();        System.out.println("生成的随机字符"+str);        String MDStr=MD5Util.md5(str);        System.out.println("生成的随机字符加密之后"+MDStr);   } ​ }

MD5依赖

复制代码
1
2
3
4
5
6
7
<dependency>  <groupId>commons-codec</groupId>  <artifactId>commons-codec</artifactId>  <version>1.10</version> </dependency> <dependency>  <groupId>org.apache.commons</groupId>

id生成部分

MD5加密算法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.apache.commons.codec.digest.DigestUtils; ​ public class MD5Util { ​ public static String md5(String src) { return DigestUtils.md5Hex(src); } ​ private static final String salt = "1a2b3c4d"; ​ public static String idMd5(String inputPass) { String str = ""+salt.charAt(0)+salt.charAt(2) + inputPass +salt.charAt(5) + salt.charAt(4); System.out.println(str); return md5(str); } ​ }

程序运行结果

全文转载点此链接

最后

以上就是还单身项链最近收集整理的关于设计一个分布式的全局唯一ID生成器1、要求长度为8的全部内容,更多相关设计一个分布式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(96)

评论列表共有 0 条评论

立即
投稿
返回
顶部