1. 程式人生 > 其它 >UUID雪花演算法,自動生成ID方法

UUID雪花演算法,自動生成ID方法

UUID雪花演算法,自動生成ID方法
//建立包名uuid,包下3個實體類
//IdWorker

/******************************************************************************
* Copyright (C) 2018-2022 Yantai HaiYi Software Co., Ltd
* All Rights Reserved.
* Developed by Yantai Haiyi Software . Without the prior written consent of the company hereto,
* No party may use, copy, modify or release this software.
*****************************************************************************/
package com.ruoyi.system.uuid;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;


import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;





/**
* twitter的SnowFlake演算法獲取18位的數字id
*
* @author liulei
*
*<p>Modification History:</p>
*<p>Date Author Description</p>
*<p>------------------------------------------------------------------</p>
*<p>2018年8月23日 liulei 新建</p>
*/
public class IdWorker {

private static Long p1;
private static Long p2;
private static SnowflakeIdWorker snowflakeIdWorker;
private IdWorker(){}

/**
* 獲取一個id
* @return
* @author liulei - 2018年8月23日 :
*/
public static String getId() {
if(snowflakeIdWorker == null) {
if( p1 == null || p2 == null ){
getP1andP2();
}
snowflakeIdWorker = new SnowflakeIdWorker(p1, p2);
}
return snowflakeIdWorker.nextId();
}

private static void getP1andP2(){
try{
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();