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