SpringBoot 2.0集成百度UidGenerator

UidGenerator是百度开源的Java语言实现,基于Snowflake算法的唯一ID生成器。

Github:https://github.com/baidu/uid-generator
参考:https://github.com/baidu/uid-generator/blob/master/README.zh_cn.md

打包到本地Maven仓库或发布依赖到私服

下载源码:https://github.com/baidu/uid-generator ,并依据官网创建好表

如需修改数据库连接池

<!--<dependency>
<groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.19</version>
    <scope>test</scope>
</dependency>-->
<!--更换数据库连接池为HikariCP-->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>2.7.9</version>
</dependency>

修改数据库连接池参数信息

<!-- 数据源配置 -->
<bean id="dataSource"  class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <property name="driverClassName" value="${mysql.driver}" />
    <property name="connectionTestQuery" value="select 1" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="readOnly" value="false" />
    <property name="connectionTimeout" value="30000" />
    <property name="idleTimeout" value="600000" />
    <property name="maxLifetime" value="1800000" />
    <property name="maximumPoolSize" value="15" />
    <!--
    dataSource.setMaximumPoolSize(15);-->
</bean>
mysql.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.xx.xx:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=/Akk2pyqQ8ohJN8tOmGwdPr64BNxG/hnjXZqZrp2d7X8BNk1

执行mvn clean install

Spring Boot工程集成

(1)创建数据库表

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: CONTAINER(1), ACTUAL(2), FAKE(3)',
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;

(2)引入依赖

<dependency>
    <groupId>com.baidu.fsg</groupId>
    <artifactId>uid-generator</artifactId>
    <version>1.0.0-SNAPSHOT</version>
</dependency>

(3)MyBatis配置信息

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations:
  - classpath*:mybatis/mapper/*Mapper.xml

(4)拷贝WorkerNodeDAO.java到自己的SpringBoot项目中,命名成WorkerNodeMapper.java

(5)拷贝WORKER_NODE.xml到自己的SpringBoot项目中,命名成WorkerNodeMapper.xml,注意修改namespace

(6)拷贝DisposableWorkerIdAssigner.java到自己的SpringBoot项目中,修改注入的WorkerNodeDAOWorkerNodeMapper

(7)创建配置类

import com.baidu.fsg.uid.impl.CachedUidGenerator;
import com.share.service.DisposableWorkerIdAssigner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * https://github.com/baidu/uid-generator/blob/master/README.zh_cn.md
 * 百度id生成器
 * 两种生成器: DefaultUidGenerator、CachedUidGenerator。如对UID生成性能有要求, 请使用CachedUidGenerator
 * 对应Spring配置分别为: default-uid-spring.xml、cached-uid-spring.xml
 */
@Configuration
public class CachedUidGeneratorConfig {

    /**
     * 用完即弃的WorkerIdAssigner, 依赖DB操作
     * @return
     */
    @Bean
    public DisposableWorkerIdAssigner disposableWorkerIdAssigner() {
        return new DisposableWorkerIdAssigner();
    }

    @Bean
    public CachedUidGenerator cachedUidGenerator(DisposableWorkerIdAssigner disposableWorkerIdAssigner) {
        CachedUidGenerator cachedUidGenerator = new CachedUidGenerator();
        cachedUidGenerator.setWorkerIdAssigner(disposableWorkerIdAssigner);
        //以下为可选配置, 如未指定将采用默认值
        cachedUidGenerator.setTimeBits(29);
        cachedUidGenerator.setWorkerBits(21);
        cachedUidGenerator.setSeqBits(13);
        cachedUidGenerator.setEpochStr("2016-09-20");

        //RingBuffer size扩容参数, 可提高UID生成的吞吐量
        //默认:3, 原bufferSize=8192, 扩容后bufferSize= 8192 << 3 = 65536
        cachedUidGenerator.setBoostPower(3);
        // 指定何时向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线程时间间隔, 单位:秒
        cachedUidGenerator.setScheduleInterval(60L);

        //拒绝策略: 当环已满, 无法继续填充时
        //默认无需指定, 将丢弃Put操作, 仅日志记录. 如有特殊需求, 请实现RejectedPutBufferHandler接口(支持Lambda表达式)
        //<property name="rejectedPutBufferHandler" ref="XxxxYourPutRejectPolicy"></property>
        //cachedUidGenerator.setRejectedPutBufferHandler();
        //拒绝策略: 当环已空, 无法继续获取时 -->
        //默认无需指定, 将记录日志, 并抛出UidGenerateException异常. 如有特殊需求, 请实现RejectedTakeBufferHandler接口(支持Lambda表达式) -->
        //<property name="rejectedTakeBufferHandler" ref="XxxxYourTakeRejectPolicy"></property>

        return cachedUidGenerator;
    }
}

(8)Controller测试

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UidGenerator uidGenerator;

    @GetMapping("/uid")
    public String uid() {
        long time1 = System.nanoTime();
        long uid = uidGenerator.getUID();
        long time2 = System.nanoTime();
        System.out.println(time2-time1);
        System.out.println(uidGenerator.parseUID(uid));
        System.out.println("-----------------------------");
        long timeMillis = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            uidGenerator.getUID();
        }
        long timeMillis2 = System.currentTimeMillis();
        System.out.println("耗时:" + (timeMillis2-timeMillis));
        return String.valueOf(uid);
    }
    ....
}

(9)启动工程,访问:http://localhost:8080/user/uid

控制台打印(本地生成10000000条id耗时913ms)

注:每次启动项目work_node表都会有一条日志

第三方spring-boot-starter

uid-generator-spring-boot-starter: https://github.com/wujun234/uid-generator-spring-boot-starter

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/04/01/springboot-2-integration-with-baidu-uidgenerator/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
SpringBoot 2.0集成百度UidGenerator
UidGenerator是百度开源的Java语言实现,基于Snowflake算法的唯一ID生成器。 Github:https://github.com/baidu/uid-generator 参考:https://github.com/baid……
<<上一篇
下一篇>>
文章目录
关闭
目 录