IdWorker 增加 -DworkerId -DdatacenterId 参数

This commit is contained in:
thinkgem
2022-02-28 17:48:21 +08:00
parent 005b0079ca
commit 0901144fb4

View File

@@ -6,6 +6,8 @@ package com.jeesite.common.idgen;
import java.util.Random; import java.util.Random;
import org.apache.commons.lang3.StringUtils;
/** /**
* 来自于twitter项目snowflake的id产生方案全局唯一时间有序。 * 来自于twitter项目snowflake的id产生方案全局唯一时间有序。
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加)) * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
@@ -42,23 +44,39 @@ public class IdWorker {
private final long datacenterId; private final long datacenterId;
public IdWorker(long workerId, long datacenterId) { public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) { String wid = System.getProperty("workerId");
if (workerId == -1){ if (StringUtils.isNotBlank(wid)) {
this.workerId = new Random().nextInt((int)maxWorkerId); try {
}else{ workerId = Integer.parseInt(wid);
} catch (Exception e) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"worker Id can't be greater than %d or less than 0"); "jvm param -DworkerId can't be greater than %d or less than 0");
} }
}
String dcid = System.getProperty("datacenterId");
if (StringUtils.isNotBlank(dcid)) {
try {
workerId = Integer.parseInt(dcid);
} catch (Exception e) {
throw new IllegalArgumentException(
"jvm param -DdatacenterId can't be greater than %d or less than 0");
}
}
if (workerId == -1){
workerId = new Random().nextInt((int)maxWorkerId);
}
if (datacenterId == -1){
datacenterId = new Random().nextInt((int)maxDatacenterId);
}
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(
"worker Id can't be greater than %d or less than 0");
}else{ }else{
this.workerId = workerId; this.workerId = workerId;
} }
if (datacenterId > maxDatacenterId || datacenterId < 0) { if (datacenterId > maxDatacenterId || datacenterId < 0) {
if (datacenterId == -1){ throw new IllegalArgumentException(
this.datacenterId = new Random().nextInt((int)maxDatacenterId); "datacenter Id can't be greater than %d or less than 0");
}else{
throw new IllegalArgumentException(
"datacenter Id can't be greater than %d or less than 0");
}
}else{ }else{
this.datacenterId = datacenterId; this.datacenterId = datacenterId;
} }