UidGenerator是百度开源的Java语言实现,基于Snowflake算法的唯一ID生成器。而且,它非常适合虚拟环境,比如:Docker。另外,它通过消费未来时间克服了雪花算法的并发限制。UidGenerator提前生成ID并缓存在RingBuffer中。 压测结果显示,单个实例的QPS能超过6000,000。

集成方法:

1.下载

https://github.com/baidu/uid-generator

2.修改一下项目的版本

 <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.0</version>
        </dependency>

3.将cached-uid-spring.xml copy 到 resources 的 config 目录中。

并增加一个配置类

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource(locations = {"classpath:config/cached-uid-spring.xml"})
public class UidGeneratorConf {
}
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" />
        <property name="timeBits" value="30" />
        <property name="workerBits" value="20"/>
        <property name="epochStr" value="2019-05-10"/>

    </bean>

</beans>

 

4.创建一张表WORKER_NODE

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;

5.增加 mybatis map 文件的配置

mapper-locations: classpath*:/mapper/sys/core/*.map.xml,classpath*:/mapper/WORKER_NODE.xml

6.增加mybatis dao 类扫描

@MapperScan({"com.baidu.fsg"})

7.增加一个ID产类

public class UidUtil {


    /**
     * 使用百度UID获取唯一ID
     * @return
     */
    public static long genId(){
        UidGenerator uidGenerator= AppBeanUtil.getBean("cachedUidGenerator");
        return  uidGenerator.getUID();
    }
}

8.使用单元测试产生ID

@RunWith(SpringRunner.class)
@SpringBootTest
public class IdTest {


    @Test
    public void genIdTest(){
        long str=UidUtil.genId();
        System.err.println(str);

    }
}

 9.ID产生实现原理如下:

https://www.jianshu.com/p/5509cc1b9a94

posted on 2019-05-12 22:10  自由港  阅读(5870)  评论(0编辑  收藏  举报