java 全局唯一id_Java生成全局唯一ID代码演示

看了GitHub上的两个生成唯一ID的算法程序(一个出自百度,一个出自美团),打算运行着试试看,至于原理什么的文档上讲得很详细了,此处不再一一粘贴了,此处只演示代码

百度UID生成器

Maven依赖

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 <?xml version="1.0" encoding="UTF-8"?>

2

3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4 4.0.0

5

6 com.cjs.example

7 uid-generator-demo

8 0.0.1-SNAPSHOT

9 jar

10

11 uid-generator-demo

12

13

14

15 org.springframework.boot

16 spring-boot-starter-parent

17 2.0.3.RELEASE

18

19

20

21

22 UTF-8

23 UTF-8

24 1.8

25

26

27

28

29 org.mybatis.spring.boot

30 mybatis-spring-boot-starter

31 1.3.2

32

33

34 mysql

35 mysql-connector-java

36 5.1.46

37

38

39

40 org.apache.commons

41 commons-collections4

42 4.2

43

44

45 org.apache.commons

46 commons-lang3

47 3.7

48

49

50

51 org.springframework.boot

52 spring-boot-starter-test

53 test

54

55

56

57

58

59

60 org.springframework.boot

61 spring-boot-maven-plugin

62

63

64

65

66

48304ba5e6f9fe08f3fa1abda7d326ab.png

SQL脚本

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 DROP DATABASE IF EXISTS `mytest`;

2 CREATE DATABASE `mytest` ;

3 use `mytest`;

4 DROP TABLE IF EXISTS WORKER_NODE;

5 CREATE TABLE WORKER_NODE

6 (

7 ID BIGINT NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',

8 HOST_NAME VARCHAR(64) NOT NULL COMMENT 'host name',

9 PORT VARCHAR(64) NOT NULL COMMENT 'port',

10 TYPE INT NOT NULL COMMENT 'node type: ACTUAL or CONTAINER',

11 LAUNCH_DATE DATE NOT NULL COMMENT 'launch date',

12 MODIFIED TIMESTAMP NOT NULL COMMENT 'modified time',

13 CREATED TIMESTAMP NOT NULL COMMENT 'created time',

14 PRIMARY KEY(ID)

15 )COMMENT='DB WorkerID Assigner for UID Generator',ENGINE = INNODB;

48304ba5e6f9fe08f3fa1abda7d326ab.png

mapper文件

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 <?xml version="1.0" encoding="UTF-8"?>

2

3

4

5 type="com.cjs.example.baidu.uid.worker.entity.WorkerNodeEntity">

6

7

8

9

10

11

12

13

14

15

16 parameterType="com.cjs.example.baidu.uid.worker.entity.WorkerNodeEntity">

17 INSERT INTO WORKER_NODE

18 (HOST_NAME,

19 PORT,

20 TYPE,

21 LAUNCH_DATE,

22 MODIFIED,

23 CREATED)

24 VALUES (

25 #{hostName},

26 #{port},

27 #{type},

28 #{launchDate},

29 NOW(),

30 NOW())

31

32

33

34 SELECT

35 ID,

36 HOST_NAME,

37 PORT,

38 TYPE,

39 LAUNCH_DATE,

40 MODIFIED,

41 CREATED

42 FROM

43 WORKER_NODE

44 WHERE

45 HOST_NAME = #{host} AND PORT = #{port}

46

47

48304ba5e6f9fe08f3fa1abda7d326ab.png

application.yml配置

48304ba5e6f9fe08f3fa1abda7d326ab.png

spring:

datasource:

url: jdbc:mysql://localhost:3306/mytest

username: root

password: 123456

driver-class-name: com.mysql.jdbc.Driver

mybatis:

mapper-locations: classpath:mapper/*Mapper.xml

48304ba5e6f9fe08f3fa1abda7d326ab.png

Spring Bean配置

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 package com.cjs.example;

2

3 import com.cjs.example.baidu.uid.impl.CachedUidGenerator;

4 import com.cjs.example.baidu.uid.impl.DefaultUidGenerator;

5 import com.cjs.example.baidu.uid.worker.DisposableWorkerIdAssigner;

6 import com.cjs.example.baidu.uid.worker.WorkerIdAssigner;

7 import org.springframework.beans.factory.annotation.Autowired;

8 import org.springframework.boot.SpringApplication;

9 import org.springframework.boot.autoconfigure.SpringBootApplication;

10 import org.springframework.context.annotation.Bean;

11 import org.springframework.jdbc.core.JdbcTemplate;

12 import org.springframework.transaction.annotation.EnableTransactionManagement;

13

14 @EnableTransactionManagement

15 @SpringBootApplication

16 public class UidGeneratorDemoApplication {

17

18 public static void main(String[] args) {

19 SpringApplication.run(UidGeneratorDemoApplication.class, args);

20 }

21

22 @Autowired

23 private WorkerIdAssigner workerIdAssigner;

24

25 @Bean

26 public DefaultUidGenerator defaultUidGenerator() {

27 DefaultUidGenerator defaultUidGenerator = new DefaultUidGenerator();

28 defaultUidGenerator.setWorkerIdAssigner(workerIdAssigner);

29 defaultUidGenerator.setTimeBits(29);

30 defaultUidGenerator.setWorkerBits(21);

31 defaultUidGenerator.setSeqBits(13);

32 defaultUidGenerator.setEpochStr("2018-07-21");

33 return defaultUidGenerator;

34 }

35

36 @Bean

37 public DisposableWorkerIdAssigner disposableWorkerIdAssigner() {

38 return new DisposableWorkerIdAssigner();

39 }

40

41 @Bean

42 public CachedUidGenerator cachedUidGenerator() {

43 CachedUidGenerator cachedUidGenerator = new CachedUidGenerator();

44 cachedUidGenerator.setWorkerIdAssigner(workerIdAssigner);

45 cachedUidGenerator.setTimeBits(29);

46 cachedUidGenerator.setWorkerBits(21);

47 cachedUidGenerator.setSeqBits(13);

48 cachedUidGenerator.setEpochStr("2018-07-21");

49 return cachedUidGenerator;

50 }

51

52 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

测试

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 package com.cjs.example;

2

3 import com.cjs.example.baidu.uid.impl.CachedUidGenerator;

4 import com.cjs.example.baidu.uid.impl.DefaultUidGenerator;

5 import com.cjs.example.meituan.idleaf.IdLeafService;

6 import org.junit.Test;

7 import org.junit.runner.RunWith;

8 import org.springframework.beans.factory.annotation.Autowired;

9 import org.springframework.beans.factory.annotation.Qualifier;

10 import org.springframework.boot.test.context.SpringBootTest;

11 import org.springframework.test.context.junit4.SpringRunner;

12

13 @RunWith(SpringRunner.class)

14 @SpringBootTest

15 public class UidGeneratorDemoApplicationTests {

16

17 @Autowired

18 @Qualifier("defaultUidGenerator")

19 private DefaultUidGenerator defaultUidGenerator;

20

21 @Autowired

22 @Qualifier("cachedUidGenerator")

23 private CachedUidGenerator cachedUidGenerator;

24

25 26 27

28 @Test

29 public void testSerialGenerate() {

30 long uid = defaultUidGenerator.getUID();

31 System.out.println(uid);

32 System.out.println(defaultUidGenerator.parseUID(uid));

33 }

34

35 @Test

36 public void testSerialGenerate2() {

37 long uid = cachedUidGenerator.getUID();

38 System.out.println(uid);

39 System.out.println(cachedUidGenerator.parseUID(uid));

40 }

41

42 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

2eba3099c1ed5b71f5ba8b69639db920.png

1f92f34cd1aa306619f06eced57f1801.png

美团UID生成器

Maven依赖

1

2 org.apache.ignite

3 ignite-zookeeper

4 2.4.0

5

SQL脚本

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 DROP TABLE IF EXISTS `id_segment`;

2

3 CREATE TABLE `id_segment` (

4 `biz_tag` varchar(50) DEFAULT NULL COMMENT '业务标识',

5 `max_id` bigint(20) DEFAULT NULL COMMENT '分配的id号段的最大值',

6 `p_step` bigint(20) DEFAULT NULL COMMENT '步长',

7 `last_update_time` datetime DEFAULT NULL,

8 `current_update_time` datetime DEFAULT NULL

9 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='号段存储表';

10

11 insert into `id_segment`(`biz_tag`,`max_id`,`p_step`,`last_update_time`,`current_update_time`) values ('Order',60,20,'2018-07-21 15:44:02','2018-07-21 16:25:07');

48304ba5e6f9fe08f3fa1abda7d326ab.png

Spring Bean配置

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 package com.cjs.example;

2

3 import com.cjs.example.meituan.idleaf.IdLeafService;

4 import com.cjs.example.meituan.idleaf.support.MysqlIdLeafServiceImpl;

5 import org.springframework.beans.factory.annotation.Autowired;

6 import org.springframework.boot.SpringApplication;

7 import org.springframework.boot.autoconfigure.SpringBootApplication;

8 import org.springframework.context.annotation.Bean;

9 import org.springframework.jdbc.core.JdbcTemplate;

10 import org.springframework.transaction.annotation.EnableTransactionManagement;

11

12 @EnableTransactionManagement

13 @SpringBootApplication

14 public class UidGeneratorDemoApplication {

15

16 public static void main(String[] args) {

17 SpringApplication.run(UidGeneratorDemoApplication.class, args);

18 }

19

20 @Autowired

21 private JdbcTemplate jdbcTemplate;

22

23 @Bean(initMethod = "init")

24 public IdLeafService idLeafService() {

25 MysqlIdLeafServiceImpl mysqlIdLeafService = new MysqlIdLeafServiceImpl();

26 mysqlIdLeafService.setJdbcTemplate(jdbcTemplate);

27 mysqlIdLeafService.setAsynLoadingSegment(true);

28 mysqlIdLeafService.setBizTag("Order");

29 return mysqlIdLeafService;

30 }

31 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

测试

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 @Autowired

2 private IdLeafService idLeafService;

3

4 @Test

5 public void testSerialGenerate3() {

6 Long id = idLeafService.getId();

7 System.out.println(id);

8 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

2d7afccf31c0a14e92bfd739c4def7f4.png

50794f94faab1d7e77c34320f4a18532.png

个人感觉无论是从文档,原理,还是代码,觉得还是百度的那个比较好用(哇咔咔O(∩_∩)O哈哈~)

还有一个Redis的方案感觉也不错

完整代码上传至  https://github.com/chengjiansheng/uid-generator-demo.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值