我是靠谱客的博主 优秀白云,最近开发中收集的这篇文章主要介绍编号生成器,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

package new_package.nio;
import org.apache.commons.lang3.StringUtils;
import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer;
import java.io.Serializable;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
public class IdGenerator {
private static final String MACHINE_ID;
private static final ThreadLocal<Integer> SEED = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
private static final int MAX = 9999;
private static final int SIZE = 32;
private static final int PREFIX_SIZE = 4;
private IdGenerator() {
}
/**
* 生成 32 位长度的编号
*
* @param prefix 前缀
* @return
*/
public static String generate(String prefix) {
if (!StringUtils.isBlank(prefix) && prefix.length() <= PREFIX_SIZE) {
int seed = (Integer) SEED.get();
int random = ThreadLocalRandom.current().nextInt(0, MAX);
String tmp = StringUtils.join(new Serializable[]{System.currentTimeMillis(), random, Thread.currentThread().getId(), MACHINE_ID, seed});
int over = tmp.length() - (32 - prefix.length());
if (over > 0) {
tmp = StringUtils.substring(tmp, over);
} else {
tmp = StringUtils.leftPad(tmp, SIZE - prefix.length(), '0');
}
++seed;
if (seed > 9999) {
seed = 0;
}
SEED.set(seed);
return StringUtils.join(new String[]{prefix, tmp});
} else {
throw new IllegalArgumentException("prefix illegal");
}
}
public static void main(String[] args) {
System.out.println(MACHINE_ID);
System.out.println("userNo:" + generate("U"));
}
static {
SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
MACHINE_ID = hardwareAbstractionLayer.getNetworkIFs()[0].getMacaddr().replace(":", "").toUpperCase();
}
}

<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
  • https://github.com/oshi/oshi
  • https://github.com/java-native-access/jna
  • https://enroute.osgi.org/
  • https://github.com/osgi/osgi.enroute


int num = ThreadLocalRandom.current().nextInt(0, 900) + 100;
String groupId = "G" + System.nanoTime() + Thread.currentThread().getId() + String.valueOf(num);
int c = groupId.length() - 20;
if (c > 0) {
groupId = groupId.substring(0, groupId.length() - c);
}
return groupId;

最后

以上就是优秀白云为你收集整理的编号生成器的全部内容,希望文章能够帮你解决编号生成器所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(83)

评论列表共有 0 条评论

立即
投稿
返回
顶部