V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hansonwang99
V2EX  ›  程序员

Spring Boot 工程集成全局唯一 ID 生成器 UidGenerator

  •  
  •   hansonwang99 ·
    hansonwang99 · 2018-10-25 07:52:46 +08:00 · 3623 次点击
    这是一个创建于 2012 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Profile

    本文共 823 字,阅读大约需要 3 分钟 !


    概述

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

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

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

    注: 本文首发于 My Personal Blog,欢迎光临 小站

    本文内容脑图如下:

    本文内容脑图


    基础工程创建

    只需创建一个 Multi-Moudule 的 Maven 项目即可,然后我们集成进两个 Module:

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

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

        <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 配置)

    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 如下:

    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 有两个具体的实现类,分别是 DefaultUidGeneratorCachedUidGenerator,不过官方也推荐了对于性能比较敏感的项目应使用后者,因此本文也使用 CachedUidGenerator,而对于 DefaultUidGenerator不做过多阐述。

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

    <?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,其内容如下:

    <?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配置

    @Configuration
    @ImportResource(locations = { "classpath:uid/cached-uid-spring.xml" })
    public class UidConfig {
    }
    
    • service 类创建与配置

    新建 UidGenService,引入 UidGenerator 生成 UID 的业务接口

    @Service
    public class UidGenService {
    
        @Resource
        private UidGenerator uidGenerator;
    
        public long getUid() {
            return uidGenerator.getUID();
        }
    }
    
    • controller 创建与配置

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

    @RestController
    public class UidTestController {
    
        @Autowired
        private UidGenService uidGenService;
    
        @GetMapping("/testuid")
        public String test() {
            return String.valueOf( uidGenService.getUid() );
        }
    }
    

    实验测试

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

    WORKER_NODE 表内容

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

    浏览器测试

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


    后记

    由于能力有限,若有错误或者不当之处,还请大家批评指正,一起学习交流!



    12 条回复    2018-10-25 18:49:09 +08:00
    EricFuture
        1
    EricFuture  
       2018-10-25 08:56:25 +08:00 via iPhone
    先顶帖
    li27962278
        2
    li27962278  
       2018-10-25 09:12:15 +08:00
    收藏试试
    xiaoxinshiwo
        3
    xiaoxinshiwo  
       2018-10-25 09:19:41 +08:00
    select uuid_short()
    TheWalkingDead
        4
    TheWalkingDead  
       2018-10-25 09:19:56 +08:00
    mark
    hansonwang99
        5
    hansonwang99  
    OP
       2018-10-25 09:36:20 +08:00
    大佬们也请亮出你们的 方案,一起交流交流吧
    tatelucky
        6
    tatelucky  
       2018-10-25 09:41:25 +08:00
    我的 idea 自动生成
    licoycn
        7
    licoycn  
       2018-10-25 11:25:31 +08:00
    雪花 ID
    lihongjie0209
        8
    lihongjie0209  
       2018-10-25 11:30:55 +08:00
    自增 id 有什么问题, 性能问题的话可以有一个自增 id 池
    feiyuanqiu
        9
    feiyuanqiu  
       2018-10-25 11:31:19 +08:00
    不太喜欢 snowflake 这种需要中心服务器的算法,移植了这个 golang 的 xid 方案到 java,目前还只在个人项目上使用 https://github.com/rs/xid
    Raymon111111
        10
    Raymon111111  
       2018-10-25 11:34:09 +08:00
    @lihongjie0209 会暴露你的业务量
    xuanbg
        11
    xuanbg  
       2018-10-25 11:57:05 +08:00
    @Raymon111111 如果只是加密流水号的话,我这个方案 https://www.v2ex.com/t/491836#reply0 更好一些。
    janxin
        12
    janxin  
       2018-10-25 18:49:09 +08:00
    然而 Snowflake 本身很难在现实项目中直接使用

    这个请教一下为什么?只需要有个中心发 ID 工具不就行了吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3015 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 14:13 · PVG 22:13 · LAX 07:13 · JFK 10:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.