訂單隨機生成工具

看註釋——複製即用

/**
 * @author: zyh
 * @date: 2020/6/26 10:53
 * @version: 1.0
 */

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * * 訂單編碼碼生成器,生成32位數字編碼,
 * * @生成規則 1位單號類型+17位時間戳+14位(用戶id加密&隨機數)
 */
public class OrderUtils {

    /**
     * 訂單類別頭
     */
    private static final String ORDER_CODE = "1";
    
    /**
     * 退貨類別頭
     */
    private static final String RETURN_ORDER = "2";
    
    /**
     * 退款類別頭
     */
    private static final String REFUND_ORDER = "3";

    /**
     * 隨即編碼
     */
    private static final int[] r = new int[]{7, 9, 6, 2, 8, 1, 3, 0, 5, 4};
    
    /**
     * 用戶id和隨機數總長度
     */
    private static final int maxLength = 14;

    /**
     * 根據id進行加密+加隨機數組成固定長度編碼
     */
    private static String toCode(Integer userId) {
        String idStr = userId.toString();
        StringBuilder idsbs = new StringBuilder();
        for (int i = idStr.length() - 1; i >= 0; i--) {
            idsbs.append(r[idStr.charAt(i) - '0']);
        }
        return idsbs.append(getRandom(maxLength - idStr.length())).toString();
    }

    /**
     * 生成時間戳
     */
    private static String getDateTime() {
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return ""+System.currentTimeMillis();
    }

    /**
     * 生成固定長度隨機碼
     *
     * @param n 長度
     */
    private static long getRandom(long n) {
        long min = 1, max = 9;
        for (int i = 1; i < n; i++) {
            min *= 10;
            max *= 10;
        }
        long rangeLong = (((long) (new Random().nextDouble() * (max - min)))) + min;
        return rangeLong;
    }

    /**
     * 生成不帶類別標頭的編碼
     *
     * @param userId
     */
    private static synchronized String getCode(Integer userId) {
        userId = userId == null ? 10000 : userId;
        return getDateTime() + toCode(userId);
    }


    /**
     * 生成訂單單號編碼(調用方法)
     * @param userId  網站中該用戶唯一ID 防止重複
     */

    public static String getOrderCode(Integer userId) {
        return ORDER_CODE + getCode(userId);
    }


    /**
     * 生成退貨單號編碼(調用方法)
     * @param userId 網站中該用戶唯一ID 防止重複
     */
    public static String getReturnCode(Integer userId) {
        return RETURN_ORDER + getCode(userId);
    }


    /**
     * 生成退款單號編碼(調用方法)
     * @param userId  網站中該用戶唯一ID 防止重複
     */
    public static String getRefundCode(Integer userId) {
        return REFUND_ORDER + getCode(userId);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章