好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解Spring Boot工程集成全局唯一ID生成器 UidGenerator的操作步骤

spring boot中全局唯一流水号id 生成器 集成实验

概述

流水号生成器(全局唯一 id生成器)是服务化系统的基础设施,其在保障系统的正确运行和高可用方面发挥着重要作用。而关于流水号生成算法首屈一指的当属 snowflake 雪花算法,然而 snowflake本身很难在现实项目中直接使用,因此实际应用时需要一种可落地的方案。

uidgenerator 由百度开发,是java实现的, 基于 snowflake算法的唯一id生成器。uidgenerator以组件形式工作在应用项目中, 支持自定义workerid位数和初始化策略, 从而适用于 docker等虚拟化环境下实例自动重启、漂移等场景。

本文就在项目中来集成 uidgenerator这一工程来作为项目的全局唯一 id生成器。

本文内容脑图如下:

基础工程创建

只需创建一个 multi-moudule的 maven项目即可,然后我们集成进两个 module:

uid-generator : 源码在此 uid-consumer :消费者( 使用uid-generator产生全局唯一的流水号 )

uid-generator 模块我就不多说了,源码拿过来即可,无需任何改动;而关于 uid-consumer 模块,先在 pom.xml中添加相关依赖如下:

?

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

<dependencies>

   <dependency>

     <groupid>org.springframework.boot</groupid>

     <artifactid>spring-boot-starter-web</artifactid>

   </dependency>

   <dependency>

     <groupid>org.springframework.boot</groupid>

     <artifactid>spring-boot-starter-test</artifactid>

     <scope>test</scope>

   </dependency>

   <dependency>

     <groupid>org.mybatis.spring.boot</groupid>

     <artifactid>mybatis-spring-boot-starter</artifactid>

     <version> 1.3 . 2 </version>

   </dependency>

   <!-- for mysql-->

   <dependency>

     <groupid>mysql</groupid>

     <artifactid>mysql-connector-java</artifactid>

     <scope>runtime</scope>

     <version> 8.0 . 12 </version>

   </dependency>

   <!-- druid -->

   <dependency>

     <groupid>com.alibaba</groupid>

     <artifactid>druid-spring-boot-starter</artifactid>

     <version> 1.1 . 9 </version>

   </dependency>

   <!--必须放在最后-->

   <dependency>

     <groupid>cn.codesheep</groupid>

     <artifactid>uid-generator</artifactid>

     <version> 1.0 </version>

   </dependency>

</dependencies>

然后在 application.properties配置文件中添加一些配置(主要是 mysql和 mybatis配置)

?

1

2

3

4

5

6

7

server.port= 9999

spring.datasource.url=jdbc:mysql: //xxx.xxx.xxx.xxx:3306/xxx?useunicode=true&characterencoding=utf-8&usessl=false

spring.datasource.username=root

spring.datasource.password=xxx

spring.datasource.driver- class -name=com.mysql.jdbc.driver

mybatis.mapper-locations=classpath:mapper/*.xml

mybatis.configuration.map-underscore-to-camel- case = true

完成之后工程缩影如下图所示:

下面我们来一步步集成 uidgenerator 的源码。

数据库建表

首先去 mysql数据库中建一个名为 worker_node 的数据表,其 sql如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

drop table if exists worker_node;

create table worker_node

(

id bigint not null auto_increment comment 'auto increment id' ,

host_name varchar( 64 ) not null comment 'host name' ,

port varchar( 64 ) not null comment 'port' ,

type int not null comment 'node type: actual or container' ,

launch_date date not null comment 'launch date' ,

modified timestamp not null comment 'modified time' ,

created timestamp not null comment 'created time' ,

primary key(id)

)

  comment= 'db workerid assigner for uid generator' ,engine = innodb;

spring详细配置

cacheduidgenerator 配置

uidgenerator 有两个具体的实现类,分别是 defaultuidgenerator 和 cacheduidgenerator ,不过官方也推荐了对于性能比较敏感的项目应使用后者,因此本文也使用 cacheduidgenerator ,而对于 defaultuidgenerator 不做过多阐述。

我们引入 uidgenerator源码中的 cached-uid-spring.xml 文件,里面都是默认配置,我目前没有做任何修改

?

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

<?xml version= "1.0" encoding= "utf-8" ?>

<beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance"

  xsi:schemalocation="

  http: //www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

  <!-- uid generator -->

  <bean id= "disposableworkeridassigner" class = "com.baidu.fsg.uid.worker.disposableworkeridassigner" />

  <bean id= "cacheduidgenerator" class = "com.baidu.fsg.uid.impl.cacheduidgenerator" >

  <property name= "workeridassigner" ref= "disposableworkeridassigner" />

  <!-- 以下为可选配置, 如未指定将采用默认值 -->

  <!-- ringbuffer size扩容参数, 可提高uid生成的吞吐量. -->

  <!-- 默认: 3 , 原buffersize= 8192 , 扩容后buffersize= 8192 << 3 = 65536 -->

  <!--<property name= "boostpower" value= "3" ></property>-->

 

  <!-- 指定何时向ringbuffer中填充uid, 取值为百分比( 0 , 100 ), 默认为 50 -->

  <!-- 举例: buffersize= 1024 , paddingfactor= 50 -> threshold= 1024 * 50 / 100 = 512 . -->

  <!-- 当环上可用uid数量 < 512 时, 将自动对ringbuffer进行填充补全 -->

  <!--<property name= "paddingfactor" value= "50" ></property>-->

 

  <!-- 另外一种ringbuffer填充时机, 在schedule线程中, 周期性检查填充 -->

  <!-- 默认:不配置此项, 即不实用schedule线程. 如需使用, 请指定schedule线程时间间隔, 单位:秒 -->

  <!--<property name= "scheduleinterval" value= "60" ></property>-->

 

  <!-- 拒绝策略: 当环已满, 无法继续填充时 -->

  <!-- 默认无需指定, 将丢弃put操作, 仅日志记录. 如有特殊需求, 请实现rejectedputbufferhandler接口(支持lambda表达式) -->

  <!--<property name= "rejectedputbufferhandler" ref= "xxxxyourputrejectpolicy" ></property>-->

 

  <!-- 拒绝策略: 当环已空, 无法继续获取时 -->

  <!-- 默认无需指定, 将记录日志, 并抛出uidgenerateexception异常. 如有特殊需求, 请实现rejectedtakebufferhandler接口(支持lambda表达式) -->

  <!--<property name= "rejectedputbufferhandler" ref= "xxxxyourputrejectpolicy" ></property>-->

 

  </bean>

</beans>

mybatis mapper xml 配置

即原样引入 uidgenerator源码中关于工作节点(worker node)操作的 mapper xml 文件: worker_node.xml ,其内容如下:

?

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

39

40

41

42

43

44

45

<?xml version= "1.0" encoding= "utf-8" ?>

<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace= "com.baidu.fsg.uid.worker.dao.workernodedao" >

  <resultmap id= "workernoderes"

    type= "com.baidu.fsg.uid.worker.entity.workernodeentity" >

  <id column= "id" jdbctype= "bigint" property= "id" />

  <result column= "host_name" jdbctype= "varchar" property= "hostname" />

  <result column= "port" jdbctype= "varchar" property= "port" />

  <result column= "type" jdbctype= "integer" property= "type" />

  <result column= "launch_date" jdbctype= "date" property= "launchdate" />

  <result column= "modified" jdbctype= "timestamp" property= "modified" />

  <result column= "created" jdbctype= "timestamp" property= "created" />

  </resultmap>

  <insert id= "addworkernode" usegeneratedkeys= "true" keyproperty= "id"

  parametertype= "com.baidu.fsg.uid.worker.entity.workernodeentity" >

  insert into worker_node

  (host_name,

  port,

  type,

  launch_date,

  modified,

  created)

  values (

  #{hostname},

  #{port},

  #{type},

  #{launchdate},

  now(),

  now())

  </insert>

  <select id= "getworkernodebyhostport" resultmap= "workernoderes" >

  select

  id,

  host_name,

  port,

  type,

  launch_date,

  modified,

  created

  from

  worker_node

  where

  host_name = #{host} and port = #{port}

  </select>

</mapper>

编写业务代码

config 类创建与配置

新建 uidconfig 类,为我们引入上文的 cached-uid-spring.xml 配置

?

1

2

3

4

@configuration

@importresource (locations = { "classpath:uid/cached-uid-spring.xml" })

public class uidconfig {

}

service 类创建与配置

新建 uidgenservice ,引入 uidgenerator 生成 uid的业务接口

?

1

2

3

4

5

6

7

8

9

10

@service

public class uidgenservice {

 

   @resource

   private uidgenerator uidgenerator;

 

   public long getuid() {

     return uidgenerator.getuid();

   }

}

controller 创建与配置

新建 uidtestcontroller ,目的是方便我们用浏览器测试接口并观察效果:

?

1

2

3

4

5

6

7

8

9

10

11

@restcontroller

public class uidtestcontroller {

 

   @autowired

   private uidgenservice uidgenservice;

 

   @getmapping ( "/testuid" )

   public string test() {

     return string.valueof( uidgenservice.getuid() );

   }

}

实验测试

我们每启动一次 spring boot工程,其即会自动去 mysql数据的 worker_node 表中插入一行关于工作节点的记录,类似下图所示:

接下来我们浏览器访问:http://localhost:9999/testuid

ok,全局唯一流水号id已经成功生成并返回!

总结

以上所述是小编给大家介绍的spring boot工程集成全局唯一id生成器 uidgenerator,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:http://www.codesheep.cn/2018/10/24/springbt-uid-generator/

查看更多关于详解Spring Boot工程集成全局唯一ID生成器 UidGenerator的操作步骤的详细内容...

  阅读:35次