雪花id new
This commit is contained in:
@ -1,8 +1,12 @@
|
|||||||
package com.chinaunicom.mall.ebtp.common.util;
|
package com.chinaunicom.mall.ebtp.common.util;
|
||||||
|
|
||||||
import cn.hutool.core.util.IdUtil;
|
import cn.hutool.core.util.IdUtil;
|
||||||
import cn.hutool.core.util.RandomUtil;
|
import org.apache.commons.lang3.RandomUtils;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.commons.lang3.SystemUtils;
|
||||||
|
|
||||||
|
import java.net.Inet4Address;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <P>配置文件参数注入</P>
|
* <P>配置文件参数注入</P>
|
||||||
@ -13,18 +17,36 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
*/
|
*/
|
||||||
public class PropertyUtils {
|
public class PropertyUtils {
|
||||||
|
|
||||||
/**
|
private final static long WORKER_ID;
|
||||||
* 终端ID
|
private final static long DATACENTER_ID;
|
||||||
*/
|
static{
|
||||||
@Value("${mconfig.work-id}")
|
WORKER_ID = getWorkId();
|
||||||
public static long WORKER_ID;
|
DATACENTER_ID =getDataCenterId();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
private static Long getWorkId(){
|
||||||
* 数据中心ID
|
try {
|
||||||
*/
|
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
|
||||||
@Value("${mconfig.datacenter-id}")
|
int[] ints = StringUtils.toCodePoints(hostAddress);
|
||||||
public static long DATACENTER_ID;
|
int sums = 0;
|
||||||
|
for(int b : ints){
|
||||||
|
sums += b;
|
||||||
|
}
|
||||||
|
return (long)(sums % 32);
|
||||||
|
} catch (UnknownHostException e) {
|
||||||
|
// 如果获取失败,则使用随机数备用
|
||||||
|
return RandomUtils.nextLong(0,31);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Long getDataCenterId() {
|
||||||
|
int[] ints = StringUtils.toCodePoints(SystemUtils.getHostName());
|
||||||
|
int sums = 0;
|
||||||
|
for (int i : ints) {
|
||||||
|
sums += i;
|
||||||
|
}
|
||||||
|
return (long) (sums % 32);
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 生成雪花id,
|
* 生成雪花id,
|
||||||
*
|
*
|
||||||
@ -40,8 +62,7 @@ public class PropertyUtils {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static long getSnowflakeLongId() {
|
public static long getSnowflakeLongId() {
|
||||||
long workerId = RandomUtil.getRandom().nextLong(31);
|
|
||||||
long datacenterId = RandomUtil.getRandom().nextLong(31);
|
return IdUtil.getSnowflake(WORKER_ID,DATACENTER_ID).nextId();
|
||||||
return IdUtil.getSnowflake(workerId, datacenterId).nextId();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user