cn.zcltd.btg.sutil.Identities Maven / Gradle / Ivy
package cn.zcltd.btg.sutil;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.UUID;
/**
* 封装各种生成唯一性ID算法的工具类.
*/
public class Identities {
/**
* 获取一个指定区间[min,max]内的随机整数
*
* @param min 最小值
* @param max 最大值
* @return String
*/
public static String random(int min, int max) {
return String.valueOf(new Random().nextInt(max - min + 1) + min);
}
/**
* 获取一个指定长度的随机整数(支持0到9位长度)
*
* @param length 长度
* @return String
*/
public static String random(int length) {
if (length <= 0) return "";
length = length > 9 ? 9 : length;
DecimalFormat format = new DecimalFormat("#");
int min = Integer.valueOf(format.format(Math.pow(10, length - 1)));
int max = Integer.valueOf(format.format(Math.pow(10, length))) - 1;
return random(min, max);
}
/**
* 获取一个原始的uuid(带中划线"-",大写)
*
* @return String
*/
public static String uuidOriginal() {
return UUID.randomUUID().toString().toUpperCase();
}
/**
* 获取一个uuid(大写)
*
* @return String
*/
public static String uuid() {
return uuidOriginal().replaceAll("-", "");
}
/**
* 获取一个流水号(当前时间戳截取timestampBeginIndex到timestampEndIndex+randomLength位随机数)
*
* @param timestampBeginIndex 开始下标
* @param timestampEndIndex 结束下标
* @param randomLength 随机数长度
* @return String
*/
public static String serialNo(int timestampBeginIndex, int timestampEndIndex, int randomLength) {
String timestamp = DateUtil.getNowTimestamp();
timestampEndIndex = timestampEndIndex <= 0 ? 0 : timestampEndIndex;
timestampEndIndex = timestampEndIndex >= timestamp.length() - 1 ? timestamp.length() - 1 : timestampEndIndex;
timestampBeginIndex = timestampBeginIndex <= 0 ? 0 : timestampBeginIndex;
timestampBeginIndex = timestampBeginIndex >= timestamp.length() - 1 ? timestamp.length() - 1 : timestampBeginIndex;
if (timestampBeginIndex > timestampEndIndex) {
int temp = timestampBeginIndex;
timestampBeginIndex = timestampEndIndex;
timestampEndIndex = temp;
}
return DateUtil.getNowTimestamp().substring(timestampBeginIndex, timestampEndIndex) + random(randomLength);
}
/**
* 获取一个流水号(当前时间年月日时分秒+6位随机数)
*
* @return String
*/
public static String serialNo() {
return serialNo(0, 14, 6);
}
}