生成32位订单号

 转载:https://blog.csdn.net/jiwengjian123/article/details/81133837?utm_source=blogxgwz0



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

 
/**
 * 订单编码码生成器,生成32位数字编码,
 * @生成规则 1位单号类型+17位时间戳+14位(用户id加密&随机数)
 * Date:2017年9月8日上午10:05:19
 * @author 
 */
public class OrderCodeFactory {

	/** 订单类别头 */
	private static final String ORDER_CODE = "1";
	/** 退货类别头 */
	private static final String RETURN_ORDER = "2";
	/** 退款类别头 */
	private static final String REFUND_ORDER = "3";
	/** 未付款重新支付别头 */
	private static final String AGAIN_ORDER = "4";
	/** 随即编码 */
	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(Long id) {
		String idStr =id.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 sdf.format(new Date());
	}

	/**
     * 生成固定长度随机码
     * @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(Long userId) {
		userId = userId == null ? 10000 : userId;
		return getDateTime() + toCode(userId);
	}

	/**
     * 生成订单单号编码
     * @param userId
     */
	public static String getOrderCode(Long userId) {
		return ORDER_CODE + getCode(userId);
	}

	/**
     * 生成退货单号编码
     * @param userId
     */
	public static String getReturnCode(long userId) {
		return RETURN_ORDER + getCode(userId);
	}
	
	/**
     * 生成退款单号编码
     * @param userId
     */
	public static String getRefundCode(long userId) {
		return REFUND_ORDER + getCode(userId);
	}
	
	/**
     * 未付款重新支付
     * @param userId
     */
	public static String getAgainCode(long userId) {
		return AGAIN_ORDER + getCode(userId);
	}
	public static void main(String[] args) {
		long userId = 13661719442L;
		String orderCode = getOrderCode(userId);
		System.out.println("orderCode="+orderCode+",length="+orderCode.length());
	}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值