Mybatis-Plus雪花id的使用以及解析機(jī)器ID和數(shù)據(jù)標(biāo)識ID實現(xiàn)
概述
分布式系統(tǒng)中,有一些需要使用全局唯一ID的場景,這種時候為了防止ID沖突可以使用36位的UUID,但是UUID有一些缺點,首先他相對比較長,另外UUID一般是無序的。
有些時候我們希望能使用一種簡單一些的ID,并且希望ID能夠按照時間有序生成。
而twitter的snowflake解決了這種需求,最初Twitter把存儲系統(tǒng)從MySQL遷移到Cassandra,因為Cassandra沒有順序ID生成機(jī)制,所以開發(fā)了這樣一套全局唯一ID生成服務(wù)。
結(jié)構(gòu)
snowflake的結(jié)構(gòu)如下(每部分用-分開):
0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
第一位為未使用,接下來的41位為毫秒級時間(41位的長度可以使用69年),然后是5位datacenterId和5位workerId(10位的長度最多支持部署1024個節(jié)點) ,最后12位是毫秒內(nèi)的計數(shù)(12位的計數(shù)順序號支持每個節(jié)點每毫秒產(chǎn)生4096個ID序號)
一共加起來剛好64位,為一個Long型。(轉(zhuǎn)換成字符串后長度最多19)
snowflake生成的ID整體上按照時間自增排序,并且整個分布式系統(tǒng)內(nèi)不會產(chǎn)生ID碰撞(由datacenter和workerId作區(qū)分),并且效率較高。經(jīng)測試snowflake每秒能夠產(chǎn)生26萬個ID。
源碼
/**
* Twitter_Snowflake<br>
* SnowFlake的結(jié)構(gòu)如下(每部分用-分開):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位標(biāo)識,由于long基本類型在Java中是帶符號的,最高位是符號位,正數(shù)是0,負(fù)數(shù)是1,所以id一般是正數(shù),最高位是0<br>
* 41位時間截(毫秒級),注意,41位時間截不是存儲當(dāng)前時間的時間截,而是存儲時間截的差值(當(dāng)前時間截 - 開始時間截)
* 得到的值),這里的的開始時間截,一般是我們的id生成器開始使用的時間,由我們程序來指定的(如下下面程序IdWorker類的startTime屬性)。41位的時間截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的數(shù)據(jù)機(jī)器位,可以部署在1024個節(jié)點,包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒內(nèi)的計數(shù),12位的計數(shù)順序號支持每個節(jié)點每毫秒(同一機(jī)器,同一時間截)產(chǎn)生4096個ID序號<br>
* 加起來剛好64位,為一個Long型。<br>
* SnowFlake的優(yōu)點是,整體上按照時間自增排序,并且整個分布式系統(tǒng)內(nèi)不會產(chǎn)生ID碰撞(由數(shù)據(jù)中心ID和機(jī)器ID作區(qū)分),并且效率較高,經(jīng)測試,SnowFlake每秒能夠產(chǎn)生26萬ID左右。
*/
public class SnowflakeIdWorker {
// ==============================Fields===========================================
/** 開始時間截 (2015-01-01) */
private final long twepoch = 1420041600000L;
/** 機(jī)器id所占的位數(shù) */
private final long workerIdBits = 5L;
/** 數(shù)據(jù)標(biāo)識id所占的位數(shù) */
private final long datacenterIdBits = 5L;
/** 支持的最大機(jī)器id,結(jié)果是31 (這個移位算法可以很快的計算出幾位二進(jìn)制數(shù)所能表示的最大十進(jìn)制數(shù)) */
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
/** 支持的最大數(shù)據(jù)標(biāo)識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)識id向左移17位(12+5) */
private final long datacenterIdShift = sequenceBits + workerIdBits;
/** 時間截向左移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的時間截 */
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==========================================
/**
* 獲得下一個ID (該方法是線程安全的)
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
//如果當(dāng)前時間小于上一次ID生成的時間戳,說明系統(tǒng)時鐘回退過這個時候應(yīng)當(dāng)拋出異常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一時間生成的,則進(jìn)行毫秒內(nèi)序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
//毫秒內(nèi)序列溢出
if (sequence == 0) {
//阻塞到下一個毫秒,獲得新的時間戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//時間戳改變,毫秒內(nèi)序列重置
else {
sequence = 0L;
}
//上次生成ID的時間截
lastTimestamp = timestamp;
//移位并通過或運算拼到一起組成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (datacenterId << datacenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}
/**
* 阻塞到下一個毫秒,直到獲得新的時間戳
* @param lastTimestamp 上次生成ID的時間截
* @return 當(dāng)前時間戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 返回以毫秒為單位的當(dāng)前時間
* @return 當(dāng)前時間(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}
//==============================Test=============================================
/** 測試 */
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ǔ)上做的升級配置!
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配置文件中增加如下配置項
mybatis-plus: #mapper-locations: classpath:mybatis/**/*Mapper.xml # 在classpath前添加星號可以使項目熱加載成功 mapper-locations: classpath*:mybatis/**/*Mapper.xml #實體掃描,多個package用逗號或者分號分隔 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)識 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 #序列接口實現(xiàn)類配置 #key-generator: com.baomidou.springboot.xxx #邏輯刪除配置(下面3個配置) logic-delete-value: 0 logic-not-delete-value: 1 #自定義SQL注入器 #sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector #自定義填充策略接口實現(xiàn) #meta-object-handler: com.baomidou.springboot.xxx configuration: map-underscore-to-camel-case: true cache-enabled: false # 這個配置會將執(zhí)行的sql打印出來,在開發(fā)或測試的時候可以用 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.原有的mapper接口增加繼承BaseMapper接口
public interface UserMapper extends BaseMapper<User>
4.實體類增加注解
在User實體類上添加@TableId的注解用來標(biāo)識實體類的主鍵,以便插件在生成主鍵雪花Id的時候找到哪個是主鍵。
@TableId @JsonFormat(shape = JsonFormat.Shape.STRING) private Long userId;
5.分頁配置
5.1 添加mybatis的一個配置類(不添加,則分頁數(shù)據(jù)中的page參數(shù)會異常)
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分頁對象。
@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
這里不再闡述,直接貼上生成的一個雪花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)識ID實現(xiàn)的文章就介紹到這了,更多相關(guān)Mybatis-Plus雪花id內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
學(xué)習(xí)Java之二叉樹的編碼實現(xiàn)過程詳解
本文將通過代碼來進(jìn)行二叉樹的編碼實現(xiàn),文中的代碼示例介紹的非常詳細(xì),對我們學(xué)習(xí)Java二叉樹有一定的幫助,感興趣的同學(xué)跟著小編一起來看看吧2023-08-08
Java中private關(guān)鍵字詳細(xì)用法實例以及解釋
這篇文章主要給大家介紹了關(guān)于Java中private關(guān)鍵字詳細(xì)用法實例以及解釋的相關(guān)資料,在Java中private是一種訪問修飾符,它可以用來控制類成員的訪問權(quán)限,文中將用法介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
Mybatis-plus多租戶項目實戰(zhàn)進(jìn)階指南
多租戶是一種軟件架構(gòu)技術(shù),在多用戶的環(huán)境下共有同一套系統(tǒng),并且要注意數(shù)據(jù)之間的隔離性,下面這篇文章主要給大家介紹了關(guān)于Mybatis-plus多租戶項目實戰(zhàn)進(jìn)階的相關(guān)資料,需要的朋友可以參考下2022-02-02
通過Spring Boot配置動態(tài)數(shù)據(jù)源訪問多個數(shù)據(jù)庫的實現(xiàn)代碼
這篇文章主要介紹了通過Spring Boot配置動態(tài)數(shù)據(jù)源訪問多個數(shù)據(jù)庫的實現(xiàn)代碼,需要的朋友可以參考下2018-03-03
詳解Spring框架下向異步線程傳遞HttpServletRequest參數(shù)的坑
這篇文章主要介紹了詳解Spring框架下向異步線程傳遞HttpServletRequest參數(shù)的坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03
Maven添加Tomcat插件實現(xiàn)熱部署代碼實例
這篇文章主要介紹了Maven添加Tomcat插件實現(xiàn)熱部署代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

