From de382f270eeafa559dda26789e6136df0c5be46a Mon Sep 17 00:00:00 2001 From: zhangqinbin <181961702@qq.com> Date: Wed, 8 Sep 2021 15:09:23 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9B=AA=E8=8A=B1id=20new?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mall/ebtp/common/util/PropertyUtils.java | 51 +++++++++++++------ 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/uboot-common/src/main/java/com/chinaunicom/mall/ebtp/common/util/PropertyUtils.java b/uboot-common/src/main/java/com/chinaunicom/mall/ebtp/common/util/PropertyUtils.java index 598ec8e..39b595a 100644 --- a/uboot-common/src/main/java/com/chinaunicom/mall/ebtp/common/util/PropertyUtils.java +++ b/uboot-common/src/main/java/com/chinaunicom/mall/ebtp/common/util/PropertyUtils.java @@ -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; /** *

配置文件参数注入

@@ -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(); } }