UidGenerator是百度開源的Java語言實現,基於Snowflake算法的惟一ID生成器。並且,它很是適合虛擬環境,好比:Docker。另外,它經過消費將來時間克服了雪花算法的併發限制。UidGenerator提早生成ID並緩存在RingBuffer中。 壓測結果顯示,單個實例的QPS能超過6000,000。
集成方法:node
1.下載git
https://github.com/baidu/uid-generatorgithub
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 目錄中。spring
並增長一個配置類緩存
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_NODEmybatis
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 類掃描app
@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