欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mybatis-Plus雪花id的使用以及解析機(jī)器ID和數(shù)據(jù)標(biāo)識(shí)ID實(shí)現(xiàn)

 更新時(shí)間:2020年08月26日 09:40:47   作者:摩羯座de杰杰陸  
這篇文章主要介紹了Mybatis-Plus雪花id的使用以及解析機(jī)器ID和數(shù)據(jù)標(biāo)識(shí)ID實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

概述

分布式系統(tǒng)中,有一些需要使用全局唯一ID的場(chǎng)景,這種時(shí)候?yàn)榱朔乐笽D沖突可以使用36位的UUID,但是UUID有一些缺點(diǎn),首先他相對(duì)比較長(zhǎng),另外UUID一般是無(wú)序的。

有些時(shí)候我們希望能使用一種簡(jiǎn)單一些的ID,并且希望ID能夠按照時(shí)間有序生成。

而twitter的snowflake解決了這種需求,最初Twitter把存儲(chǔ)系統(tǒng)從MySQL遷移到Cassandra,因?yàn)镃assandra沒(méi)有順序ID生成機(jī)制,所以開(kāi)發(fā)了這樣一套全局唯一ID生成服務(wù)。

結(jié)構(gòu)

snowflake的結(jié)構(gòu)如下(每部分用-分開(kāi)):

0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000

第一位為未使用,接下來(lái)的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))

一共加起來(lái)剛好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萬(wàn)個(gè)ID。

源碼

/**
 * Twitter_Snowflake<br>
 * SnowFlake的結(jié)構(gòu)如下(每部分用-分開(kāi)):<br>
 * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
 * 1位標(biāo)識(shí),由于long基本類(lèi)型在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í)間截 - 開(kāi)始時(shí)間截)
 * 得到的值),這里的的開(kāi)始時(shí)間截,一般是我們的id生成器開(kāi)始使用的時(shí)間,由我們程序來(lái)指定的(如下下面程序IdWorker類(lèi)的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>
 * 加起來(lái)剛好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萬(wàn)ID左右。
 */
public class SnowflakeIdWorker {

 // ==============================Fields===========================================
 /** 開(kāi)始時(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í)間戳,說(shuō)明系統(tǒng)時(shí)鐘回退過(guò)這個(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;

  //移位并通過(guò)或運(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);
  }
 }
}

以上資料轉(zhuǎn)載自該博客,點(diǎn)我!

Mybatis-Plus使用雪花id

注意:以下配置是在SpringBoot2.1.4版本以及在mybatis已經(jīng)可以使用的基礎(chǔ)上做的升級(jí)配置!

1.引入Mybatis-Plus依賴(lài)(3.1.1版本目前有些問(wèn)題,建議使用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:
 #主鍵類(lèi)型 0:"數(shù)據(jù)庫(kù)ID自增", 1:"用戶(hù)輸入ID",2:"全局唯一ID (數(shù)字類(lèi)型唯一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ù)庫(kù)大寫(xiě)下劃線轉(zhuǎn)換
 #capital-mode: true
 #序列接口實(shí)現(xiàn)類(lèi)配置
 #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打印出來(lái),在開(kāi)發(fā)或測(cè)試的時(shí)候可以用
 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.原有的mapper接口增加繼承BaseMapper接口

public interface UserMapper extends BaseMapper<User>

4.實(shí)體類(lèi)增加注解

在User實(shí)體類(lèi)上添加@TableId的注解用來(lái)標(biāo)識(shí)實(shí)體類(lèi)的主鍵,以便插件在生成主鍵雪花Id的時(shí)候找到哪個(gè)是主鍵。

@TableId
 @JsonFormat(shape = JsonFormat.Shape.STRING)
 private Long userId;

5.分頁(yè)配置

5.1 添加mybatis的一個(gè)配置類(lèi)(不添加,則分頁(yè)數(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插件配置類(lèi)
 *
 * @author lwj
 */
@EnableTransactionManagement
@Configuration
@MapperScan({"com.nis.project.*.mapper","com.nis.project.*.*.mapper"})
public class MybatisPlusConfig {

 /**
  * 分頁(yè)插件
  */
 @Bean
 public PaginationInterceptor paginationInterceptor() {
  return new PaginationInterceptor();
 }
}

5.2 java代碼示例

Controller類(lèi)中添加page分頁(yè)對(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文件中寫(xiě)的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ù)范圍過(guò)濾 -->
  ${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)文章

最新評(píng)論