Spring Boot项目集成UidGenerato的方法步骤

网友投稿 251 2023-02-13

Spring Boot项目集成UidGenerato的方法步骤

前言

UidGenerato 基于snowflake算法实现

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

准备一个maven项目,构建两个模块。分别作为使用方和提供方。(建两个模块主要是为了“造轮子”,其他模块或项目可以直接引用,无需关心uid配置,如果没有分模块,可以指忽略构建两个模块)

下载uid源码,放在项目中,开源地址 https://github.com/baidu/uid-generator

数据库建表

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

CachedUidGennerator:

    UidGenerator 有两个具体的实现类,分别是 DefaultUidGenerator 和 CachedUidGenerator, 官方推荐使用性能较强的 CachedUidGenerator。

我们直接引用 UdiGenerator源码中的 cached-uid-spring.xml文件,使用默认配置

xsi:schemaLocation="

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

http://

xsi:schemaLocation="

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

http://

引入cached-uid-spring.xml配置文件,在我们自己新建的 UidConfig中

package com.xxx.uid.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.ImportResource;

/**

* @author lishuzhen

* @date 2020/8/11 16:10

*/

@Configuration

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

public class UidConfig {

}

在另一个模块中maven引入,创建一个UidGenUtils工具类,方便使用

package com.xxxx.utils;

import com.xxx.uid.UidGenerator;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**

HBxYVMLZL* @author lishuzhen

* @date 2020/8/11 16:13

*/

@Component

public class UidGenUtils {

@Resource

private UidGenerator uidGenerator;

public long getUid() {

return uidGenerator.getUID();

}

public String getUidStr() {

return String.valueOf(uidGenerator.getUID());

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:信息聚合 软件(信息聚合网站)
下一篇:全国彩票api接口平台(全国彩票api接口平台官网)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~