Mybatis-Plus雪花id的使用以及解析機(jī)器ID和數(shù)據(jù)標(biāo)識(shí)ID實(shí)現(xiàn)
概述
分布式系統(tǒng)中,有一些需要使用全局唯一ID的場(chǎng)景,這種時(shí)候?yàn)榱朔乐笽D沖突可以使用36位的UUID,但是UUID有一些缺點(diǎn),首先他相對(duì)比較長(zhǎng),另外UUID一般是無序的。
有些時(shí)候我們希望能使用一種簡(jiǎn)單一些的ID,并且希望ID能夠按照時(shí)間有序生成。
而twitter的snowflake解決了這種需求,最初Twitter把存儲(chǔ)系統(tǒng)從MySQL遷移到Cassandra,因?yàn)镃assandra沒有順序ID生成機(jī)制,所以開發(fā)了這樣一套全局唯一ID生成服務(wù)。
結(jié)構(gòu)
snowflake的結(jié)構(gòu)如下(每部分用-分開):
0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
第一位為未使用,接下來的41位為毫秒級(jí)時(shí)間(41位的長(zhǎng)度可以使用69年),然后是5位datacenterId和5位workerId(10位的長(zhǎng)度最多支持部署1024個(gè)節(jié)點(diǎn)) ,最后12位是毫秒內(nèi)的計(jì)數(shù)(12位的計(jì)數(shù)順序號(hào)支持每個(gè)節(jié)點(diǎn)每毫秒產(chǎn)生4096個(gè)ID序號(hào))
一共加起來剛好64位,為一個(gè)Long型。(轉(zhuǎn)換成字符串后長(zhǎng)度最多19)
snowflake生成的ID整體上按照時(shí)間自增排序,并且整個(gè)分布式系統(tǒng)內(nèi)不會(huì)產(chǎn)生ID碰撞(由datacenter和workerId作區(qū)分),并且效率較高。經(jīng)測(cè)試snowflake每秒能夠產(chǎn)生26萬個(gè)ID。
源碼
/**
* Twitter_Snowflake<br>
* SnowFlake的結(jié)構(gòu)如下(每部分用-分開):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位標(biāo)識(shí),由于long基本類型在Java中是帶符號(hào)的,最高位是符號(hào)位,正數(shù)是0,負(fù)數(shù)是1,所以id一般是正數(shù),最高位是0<br>
* 41位時(shí)間截(毫秒級(jí)),注意,41位時(shí)間截不是存儲(chǔ)當(dāng)前時(shí)間的時(shí)間截,而是存儲(chǔ)時(shí)間截的差值(當(dāng)前時(shí)間截 - 開始時(shí)間截)
* 得到的值),這里的的開始時(shí)間截,一般是我們的id生成器開始使用的時(shí)間,由我們程序來指定的(如下下面程序IdWorker類的startTime屬性)。41位的時(shí)間截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的數(shù)據(jù)機(jī)器位,可以部署在1024個(gè)節(jié)點(diǎn),包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒內(nèi)的計(jì)數(shù),12位的計(jì)數(shù)順序號(hào)支持每個(gè)節(jié)點(diǎn)每毫秒(同一機(jī)器,同一時(shí)間截)產(chǎn)生4096個(gè)ID序號(hào)<br>
* 加起來剛好64位,為一個(gè)Long型。<br>
* SnowFlake的優(yōu)點(diǎn)是,整體上按照時(shí)間自增排序,并且整個(gè)分布式系統(tǒng)內(nèi)不會(huì)產(chǎn)生ID碰撞(由數(shù)據(jù)中心ID和機(jī)器ID作區(qū)分),并且效率較高,經(jīng)測(cè)試,SnowFlake每秒能夠產(chǎn)生26萬ID左右。
*/
public class SnowflakeIdWorker {
// ==============================Fields===========================================
/** 開始時(shí)間截 (2015-01-01) */
private final long twepoch = 1420041600000L;
/** 機(jī)器id所占的位數(shù) */
private final long workerIdBits = 5L;
/** 數(shù)據(jù)標(biāo)識(shí)id所占的位數(shù) */
private final long datacenterIdBits = 5L;
/** 支持的最大機(jī)器id,結(jié)果是31 (這個(gè)移位算法可以很快的計(jì)算出幾位二進(jìn)制數(shù)所能表示的最大十進(jìn)制數(shù)) */
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
/** 支持的最大數(shù)據(jù)標(biāo)識(shí)id,結(jié)果是31 */
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/** 序列在id中占的位數(shù) */
private final long sequenceBits = 12L;
/** 機(jī)器ID向左移12位 */
private final long workerIdShift = sequenceBits;
/** 數(shù)據(jù)標(biāo)識(shí)id向左移17位(12+5) */
private final long datacenterIdShift = sequenceBits + workerIdBits;
/** 時(shí)間截向左移22位(5+5+12) */
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/** 生成序列的掩碼,這里為4095 (0b111111111111=0xfff=4095) */
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/** 工作機(jī)器ID(0~31) */
private long workerId;
/** 數(shù)據(jù)中心ID(0~31) */
private long datacenterId;
/** 毫秒內(nèi)序列(0~4095) */
private long sequence = 0L;
/** 上次生成ID的時(shí)間截 */
private long lastTimestamp = -1L;
//==============================Constructors=====================================
/**
* 構(gòu)造函數(shù)
* @param workerId 工作ID (0~31)
* @param datacenterId 數(shù)據(jù)中心ID (0~31)
*/
public SnowflakeIdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// ==============================Methods==========================================
/**
* 獲得下一個(gè)ID (該方法是線程安全的)
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
//如果當(dāng)前時(shí)間小于上一次ID生成的時(shí)間戳,說明系統(tǒng)時(shí)鐘回退過這個(gè)時(shí)候應(yīng)當(dāng)拋出異常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一時(shí)間生成的,則進(jìn)行毫秒內(nèi)序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
//毫秒內(nèi)序列溢出
if (sequence == 0) {
//阻塞到下一個(gè)毫秒,獲得新的時(shí)間戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//時(shí)間戳改變,毫秒內(nèi)序列重置
else {
sequence = 0L;
}
//上次生成ID的時(shí)間截
lastTimestamp = timestamp;
//移位并通過或運(yùn)算拼到一起組成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (datacenterId << datacenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}
/**
* 阻塞到下一個(gè)毫秒,直到獲得新的時(shí)間戳
* @param lastTimestamp 上次生成ID的時(shí)間截
* @return 當(dāng)前時(shí)間戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 返回以毫秒為單位的當(dāng)前時(shí)間
* @return 當(dāng)前時(shí)間(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}
//==============================Test=============================================
/** 測(cè)試 */
public static void main(String[] args) {
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
for (int i = 0; i < 1000; i++) {
long id = idWorker.nextId();
System.out.println(Long.toBinaryString(id));
System.out.println(id);
}
}
}
Mybatis-Plus使用雪花id
注意:以下配置是在SpringBoot2.1.4版本以及在mybatis已經(jīng)可以使用的基礎(chǔ)上做的升級(jí)配置!
1.引入Mybatis-Plus依賴(3.1.1版本目前有些問題,建議使用3.1.0版本)
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.0</version> </dependency>
2.在application.yml配置文件中增加如下配置項(xiàng)
mybatis-plus: #mapper-locations: classpath:mybatis/**/*Mapper.xml # 在classpath前添加星號(hào)可以使項(xiàng)目熱加載成功 mapper-locations: classpath*:mybatis/**/*Mapper.xml #實(shí)體掃描,多個(gè)package用逗號(hào)或者分號(hào)分隔 typeAliasesPackage: com.nis.project global-config: #主鍵類型 0:"數(shù)據(jù)庫ID自增", 1:"用戶輸入ID",2:"全局唯一ID (數(shù)字類型唯一ID)", 3:"全局唯一ID UUID"; id-type: 3 #機(jī)器 ID 部分(影響雪花ID) workerId: 1 #數(shù)據(jù)標(biāo)識(shí) ID 部分(影響雪花ID)(workerId 和 datacenterId 一起配置才能重新初始化 Sequence) datacenterId: 18 #字段策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷" field-strategy: 2 #駝峰下劃線轉(zhuǎn)換 db-column-underline: true #刷新mapper 調(diào)試神器 refresh-mapper: true #數(shù)據(jù)庫大寫下劃線轉(zhuǎn)換 #capital-mode: true #序列接口實(shí)現(xiàn)類配置 #key-generator: com.baomidou.springboot.xxx #邏輯刪除配置(下面3個(gè)配置) logic-delete-value: 0 logic-not-delete-value: 1 #自定義SQL注入器 #sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector #自定義填充策略接口實(shí)現(xiàn) #meta-object-handler: com.baomidou.springboot.xxx configuration: map-underscore-to-camel-case: true cache-enabled: false # 這個(gè)配置會(huì)將執(zhí)行的sql打印出來,在開發(fā)或測(cè)試的時(shí)候可以用 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.原有的mapper接口增加繼承BaseMapper接口
public interface UserMapper extends BaseMapper<User>
4.實(shí)體類增加注解
在User實(shí)體類上添加@TableId的注解用來標(biāo)識(shí)實(shí)體類的主鍵,以便插件在生成主鍵雪花Id的時(shí)候找到哪個(gè)是主鍵。
@TableId @JsonFormat(shape = JsonFormat.Shape.STRING) private Long userId;
5.分頁配置
5.1 添加mybatis的一個(gè)配置類(不添加,則分頁數(shù)據(jù)中的page參數(shù)會(huì)異常)
package com.nis.framework.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Mybatis-Plus插件配置類
*
* @author lwj
*/
@EnableTransactionManagement
@Configuration
@MapperScan({"com.nis.project.*.mapper","com.nis.project.*.*.mapper"})
public class MybatisPlusConfig {
/**
* 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
5.2 java代碼示例
Controller類中添加page分頁對(duì)象。
@GetMapping("/list")
@ResponseBody
public Msg list(User user, HttpServletRequest request) {
Map<String, Object> params = MapDataUtil.convertDataMap(request);
user.getParams().putAll(params);
Page<User> page = startMybatisPlusPage(user);
IPage<User> userIPage = userService.selectUserList(page, user);
return Msg.success(userIPage);
}
ServiceImpl中的具體方法
@Override
@DataScope(tableAlias = "b")
public IPage<User> selectUserList(Page<User> page, User user) {
return UserMapper.selectUserList(page, user);
}
mapper接口中的代碼
IPage<User> selectUserList(@Param("pg") Page<User> page, @Param("ps") User user);
mybaits的xml文件中寫的sql代碼
<select id="selectUserList" resultType="com.nis.project.system.user.domain.User" parameterType="com.nis.project.system.user.domain.User">
select
a.user_id,
a.dept_id,
a.login_name,
a.user_name,
a.email,
a.phone_number,
a.sex,
a.avatar,
a.status,
a.login_ip,
a.login_date,
a.order_num,
b.dept_name
from sys_user a
left join sys_dept b on b.dept_id = a.dept_id
where 1=1
<if test="ps.loginName != null and ps.loginName != ''">and a.login_name like concat('%', #{ps.loginName}, '%')</if>
<if test="ps.userName != null and ps.userName != ''">and a.user_name like concat('%', #{ps.userName}, '%')</if>
<if test="ps.deptId != null and ps.deptId != ''">and b.dept_id = #{ps.deptId}</if>
<if test="ps.email != null and ps.email != ''">and a.email = #{ps.email}</if>
<if test="ps.phoneNumber != null and ps.phoneNumber != ''">and a.phone_number like concat('%', #{ps.phoneNumber}, '%')</if>
<if test="ps.params.deptIds != null and ps.params.deptIds != ''">and find_in_set(a.dept_id,#{ps.params.deptIds})</if>
<if test="ps.status != null and ps.status != ''">and a.status = #{ps.status}</if>
<!-- 數(shù)據(jù)范圍過濾 -->
${ps.params.dataScope}
order by b.ancestors,a.order_num
</select>
生成雪花ID以及解析雪花ID的機(jī)器ID和數(shù)據(jù)中心ID
1.生成雪花ID
這里不再闡述,直接貼上生成的一個(gè)雪花ID;1146667501642584065
2.解析雪花ID的機(jī)器ID和數(shù)據(jù)中心ID
SELECT (1146667501642584065>>12)&0x1f as workerId,(1146667501642584065>>17)&0x1f as datacenterId;
結(jié)果圖:



到此這篇關(guān)于Mybatis-Plus雪花id的使用以及解析機(jī)器ID和數(shù)據(jù)標(biāo)識(shí)ID實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Mybatis-Plus雪花id內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
學(xué)習(xí)Java之二叉樹的編碼實(shí)現(xiàn)過程詳解
本文將通過代碼來進(jìn)行二叉樹的編碼實(shí)現(xiàn),文中的代碼示例介紹的非常詳細(xì),對(duì)我們學(xué)習(xí)Java二叉樹有一定的幫助,感興趣的同學(xué)跟著小編一起來看看吧2023-08-08
Java中private關(guān)鍵字詳細(xì)用法實(shí)例以及解釋
這篇文章主要給大家介紹了關(guān)于Java中private關(guān)鍵字詳細(xì)用法實(shí)例以及解釋的相關(guān)資料,在Java中private是一種訪問修飾符,它可以用來控制類成員的訪問權(quán)限,文中將用法介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
Mybatis-plus多租戶項(xiàng)目實(shí)戰(zhàn)進(jìn)階指南
多租戶是一種軟件架構(gòu)技術(shù),在多用戶的環(huán)境下共有同一套系統(tǒng),并且要注意數(shù)據(jù)之間的隔離性,下面這篇文章主要給大家介紹了關(guān)于Mybatis-plus多租戶項(xiàng)目實(shí)戰(zhàn)進(jìn)階的相關(guān)資料,需要的朋友可以參考下2022-02-02
通過Spring Boot配置動(dòng)態(tài)數(shù)據(jù)源訪問多個(gè)數(shù)據(jù)庫的實(shí)現(xiàn)代碼
這篇文章主要介紹了通過Spring Boot配置動(dòng)態(tài)數(shù)據(jù)源訪問多個(gè)數(shù)據(jù)庫的實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-03-03
詳解Spring框架下向異步線程傳遞HttpServletRequest參數(shù)的坑
這篇文章主要介紹了詳解Spring框架下向異步線程傳遞HttpServletRequest參數(shù)的坑,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03
LeetCode程序員面試題之無重復(fù)字符的最長(zhǎng)子串
Java計(jì)算無重復(fù)字符的最長(zhǎng)子串是一種常見的字符串處理算法,它的目的是找出一個(gè)字符串中無重復(fù)字符的最長(zhǎng)子串。該算法可以很好地解決一些字符串處理問題,比如尋找字符串中重復(fù)字符的位置,以及計(jì)算字符串中無重復(fù)字符的最長(zhǎng)子串的長(zhǎng)度。2023-02-02
Maven添加Tomcat插件實(shí)現(xiàn)熱部署代碼實(shí)例
這篇文章主要介紹了Maven添加Tomcat插件實(shí)現(xiàn)熱部署代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04

