IdWorker 增加 -DworkerId -DdatacenterId 参数
This commit is contained in:
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user