编号生成器

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.oshigroupId>
            <artifactId>oshi-coreartifactId>
            <version>4.2.1version>
        dependency>

        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.9version>
        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;

你可能感兴趣的:(框架使用)