生成序列号(幂等)

1、source+唯一序列号构成唯一字段入库

2、借助redis的自增指令实现唯一(incr指令 )

/**
 * 生成唯一流水号借助UUID
 * 还可借助redis或者数据库
 * @author xpzhang
 *
 */
public class IdempotentTest {

    
    public static void main(String[] args) {
    	ArrayList<String> arrayList = new ArrayList<>();
    	for(int i=0;i<10000;i++) {
    		String uniqueIdentifier = getUniqueIdentifier();
    		System.out.println(uniqueIdentifier);
    		arrayList.add(uniqueIdentifier);
    	}
    	
    	int size = arrayList.stream().distinct().collect(Collectors.toList()).size();
    	System.out.println(size+"==?"+arrayList.size());
    }
    /**
     * 获取全局流水号
     * @return prefix +yyMMDD+0123
     */
    public static String getUniqueIdentifier() {
    	UUID uuid = UUID.randomUUID();
    	// 4位数字
    	String uuidString=uuid.toString().replace("-", "").toUpperCase();
    	// 当前日期 yyyyMMdd 
    	String currentDate = formatDate(new Date());
    	
    	String prefix="AOP";
		return prefix+currentDate+uuidString;
    	
    }
    
    /**
     * 格式化日期
     * @param date
     * @return
     */
    public static String formatDate(Date date){
        String formatDate=null;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            formatDate = simpleDateFormat.format(date);
        } catch (Exception e) {
            //logger.error("时间格式化异常",e);
        }
        return formatDate;
    }
    
    /**
     * String转为Date日期格式
     * @param s
     * @return
     */
    public static Date stringToDate(String s){
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd");
        Date date=null;
        try {
            date = dateFormat.parse(s);
        } catch (ParseException e) {
            //logger.error("String转为date异常",e);
        }
        return date;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值