获取不重复随机数分享



import java.net.InetAddress;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * @author yy
 * @date 2017年4月12日 下午4:48:42
 * @description TODO 随机数相关
 * @tag 
 */
public class UUIDUtil {

	private static AtomicInteger sort=new AtomicInteger(0);
	private static Random random=new Random();
	public static String getSort() {
		int s = sort.incrementAndGet();
		if(s>=1000)
			return sort.getAndSet(1)+"";
		return s+"";
	}

	/**
	 * @title getOrderNum16 
	 * @description 获得16位订单编号
	 * @author yy
	 * @date 2017年4月12日 下午4:50:18
	 * @param prex 必须是两位
	 * @return
	 * @return String
	 */
	public static String getOrderNum16(String prex)
	{
		String result=null;
		if(prex==null || prex.length()!=2)
			throw new RuntimeException("订单号前缀必须是两位");
		String r=random.nextInt(99999)+"";
		
		result=prex+DateFormatUtils.format(new Date(), "yyMMdd")+
				StringUtils.leftPad(r, 5, "0")+
				StringUtils.leftPad(getSort(), 3, "0");
		return result;
	}
	
	/**
	 * @title getNumString 
	 * @description 获取流水号 返回prex + yyMMdd + 随机5位数 + 有序3位数
	 * @author yy
	 * @date 2017年9月11日 下午5:35:04
	 * @param prex
	 * @param len
	 * @return
	 * @return String
	 */
	public static String getNumString(String prex)
	{
		String result=null;
		String r=random.nextInt(99999)+"";
		
		result=prex+DateFormatUtils.format(new Date(), "yyMMdd")+
				StringUtils.leftPad(r, 5, "0")+
				StringUtils.leftPad(getSort(), 3, "0");
		return result;
	}
	
	/**
	 * @title uniqueOrder 
	 * @description 获得指定长度的 唯一流水号  根据JVMIP和进程区分,产生随机数+固定排序, 能保证不重复
	 * 				年月天时分秒 取12位 + (IP+pid).hashcode 取8位 + 随机len-23位数  + sort 3位
	 * 				IP+pid 的hash值冲突才有可能发生 订单号冲突,理论ip和pid都为数字区分不会发生冲突
	 * @author yy
	 * @date 2018年9月27日 上午10:29:21
	 * @param len >= 24的整数
	 * @return
	 * @return String
	 */
	public static String uniqueOrder(int len) {
		if(len<24)
			throw new RuntimeException("获取唯一流水长度不得低于24");
		// 年月天时分秒 取12位 + (IP+pid).hashcode 取8位  + 随机len-23位数  + sort 3位
		return 
				DateFormatUtils.format(new Date(), "yyMMddHHmmss")
				+StringUtils.leftPad((Math.abs((SystemUtil.getCurrentIp()+SystemUtil.getJVMThreadId()).hashCode()%100000000))+"",8,'0')
				+StringUtils.leftPad(random.nextInt((len-23)*10-1)+"",len-23,'0')
				+StringUtils.leftPad(getSort(), 3, '0');
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 10000; i++) {
//			System.out.println(UUIDUtil.getOrderNum16("DK"));
//			System.out.println(UUIDUtil.getOrderNum16("DK").length());
			System.out.println(UUIDUtil.uniqueOrder(24));
//			System.out.println(UUIDUtil.uniqueOrder(17));
//			System.out.println(UUIDUtil.uniqueOrder(20));
		}
	}
}
发布了38 篇原创文章 · 获赞 19 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/yangyongdehao30/article/details/53337756
今日推荐