封装一个流水号ID生成器

585 阅读1分钟

  概述

  ID号生成器(或:全局唯一ID生成器)是服务端系统的基础设施,而且ID号这个东西基本搞后端开发的程序员天天都要接触。而关于ID生成的算法现在业界首屈一指的当属Snowflake雪花算法。

  UidGenerator正是百度开源的一款基于Snowflake雪花算法实现的高性能唯一ID生成器。在本号前文中已经详细使用过UidGenerator,但使用过程还是比较繁杂,还需要自己去引UidGenerator组件的源码,感觉有点不方便。为此本文基于UidGenerator,再来封装一套更利于Spring Boot项目使用的ID号生成组件,命名为id-spring-boot-starter,一看名字就知道是开箱即用的。

  用法

  导入SQL脚本

  这一步肯定是省不掉,毕竟UidGenerator需要数据库支持

  配置数据库连接

  url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/demo?useUnicode=truecharacterEncoding=utf8autoReconnect=trueuseOldAliasMetadataBehavior=trueconnectionCollation=utf8mb4_unicode_cirewriteBatchedStatements=trueallowMultiQueries=true

  username: xxxxxx

  password: xxxxxx

  还是因为UidGenerator需要数据库支持

  修改Spring Boot主类

  Spring Boot应用主类上加上mybatis注解即可:

  @MapperScan({com.baidu.fsg.uid.worker.dao})

  代码使用方式

  怎么样,用法超级简单吧:

  首先用 Autowired的方式引入UidGenService类;

  直接调用UidGenService类的getUid()方法即可获得一个Long型的 ID号

  运行效果

  

运行效果


  demo源码在此,需要请自提:

  https://github.com/hansonwang99/Spring-Boot-In-Action/tree/master/test-id-spring-boot-starter

  id-spring-boot-starter源码下载

  需要组件id-spring-boot-starter源码进行自定制的,可以去github上自行下载源代码,地址在此:

  https://github.com/hansonwang99/Spring-Boot-In-Action/tree/master/id-spring-boot-starter

  几个注意点:

  由于UidGenerator需要数据库支持,因此使用前一定要导数据表,并且要配置MapperScan