订单号编码生成器

主要实现如订单号等单号生成
格式
P2020040310281670000716
(前缀)(yyyyMMddHHmm)(主机IP后三位)(32进制自增)(三位随机)
使用方式:CodeUtils.getNo(前缀);
下面是java代码,欢迎指导

主要生产java类


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author:
 * @Description:
 * @Date: Created in 下午 3:39 on 2019/8/8 0008.
 */
public class CodeUtils {
    private static final char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
            'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V' };
    private static String ip = null;
    private static AtomicLong number = new AtomicLong(0);
    private static long recordIpTime = 0;
    private static final String maxNumStr = "VVVV";
    private static final int maxLength = 4;
    private static final long maxNum = UnCompressNumber(maxNumStr);
    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
    private static final Random rand = new Random();

    /**
     * 获取一个订单编号
     * @return String
     */
    public static String getNo() {
        return getNo("P");
    }

    /**
     * 获取一个编号
     * @return String
     */
    public static String getNo(String prefix) {
        synchronized (CodeUtils.class) {
            checkIp();
            String time = getTime();
            long num1 = number.getAndIncrement();
            if (num1 > maxNum) {
                num1 = 0;
                number.set(0);
            }
            String num = CompressNumber(num1);
            while (num.length() < maxLength) {
                num = "0" + num;
            }
            if (num.length() > maxLength) {
                num = num.substring(num.length() - maxLength, num.length());
            }
            return prefix + time + ip + num + getRandNum();
        }
    }

    /**
     * 获取5位随机数
     * @return
     */
    private static String getRandNum() {
        return String.valueOf(rand.nextInt(999 - 100 + 1) + 100);
    }

    /**
     * @return String
     */
    private static String getTime() {
        String time = formatter.format(new Date());
        return time;
    }

    private static void checkIp() {
        if (ip == null) {
            getIp();
        } else {
            if (System.currentTimeMillis() - recordIpTime < 1000 * 60) {
                return;
            }
            getIp();
        }
    }

    private static void getIp() {
        try {
            ip = ServiceIpUtils.getLocalIP();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String ips[] = ip.split("\\.");
        ip = ips[ips.length - 1];
        while (ip.length() < 3) {
            ip = "0" + ip;
        }
        if (ip.length() > 3) {
            ip = ip.substring(ip.length() - 3, ip.length());
        }
        recordIpTime = System.currentTimeMillis();
    }

    /**
     * @param number
     * @return
     */
    private static String CompressNumber(long number) {
        char[] buf = new char[32];
        int charPos = 32;
        int radix = 1 << 5;
        long mask = radix - 1;
        do {
            buf[--charPos] = digits[(int) (number & mask)];
            number >>>= 5;
        } while (number != 0);
        String num = new String(buf, charPos, (32 - charPos));
        while (num.length() < maxLength) {
            num = "0" + num;
        }
        return num;
    }

    /**
     * @param decompStr
     * @return
     */
    private static long UnCompressNumber(String decompStr) {
        long result = 0;
        for (int i = decompStr.length() - 1; i >= 0; i--) {
            for (int j = 0; j < digits.length; j++) {
                if (decompStr.charAt(i) == digits[j]) {
                    result += ((long) j) << 5 * (decompStr.length() - 1 - i);
                }
            }
        }
        return result;
    }
}

获取当前主机IP


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @Author: 
 * @Description:
 * @Date: Created in 下午 4:26 on 2019/8/8 0008.
 */
public class ServiceIpUtils {
    private static Logger logger = LoggerFactory.getLogger(ServiceIpUtils.class);

    /**
     * 获取本地IP地址
     * @throws SocketException
     */
    public static String getLocalIP(String host) throws UnknownHostException, SocketException {
        if (host == null) {
            return getLocalIP();
        } else if (host.contains("localhost")) {
            String ip = getLocalIP();
            return host.replace("localhost", ip);
        } else {
            return host;
        }
    }

    /**
     * 获取本地IP地址
     * @throws SocketException
     */
    public static String getLocalIP() throws UnknownHostException, SocketException {
        if (isWindowsOS()) {
            return InetAddress.getLocalHost().getHostAddress();
        } else {
            return getLinuxLocalIp();
        }
    }

    /**
     * 判断操作系统是否是Windows
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /**
     * 获取Linux下的IP地址
     * @return IP地址
     * @throws SocketException
     */
    private static String getLinuxLocalIp() throws SocketException {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
                                    && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                                System.out.println(ipaddress);
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            logger.error("获取IP异常:", ex);
            ip = "127.000.000.001";
        }
        return ip;
    }
}

你可能感兴趣的:(java)