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
