利用redis创建自增订单号
需求:编码+日期+订单号数量 生成订单号
/**
* 获取当前日期
* @return
*/
public static String getNowDate() {
String res;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
res = format.format(new Date());
} catch (Exception e) {
e.printStackTrace();
throw new OrganizationServiceException("","时间装换错误");
}
return res;
}
/**
* 获取今天结束时间
* @return
*/
public static Date getTodayEndTime() {
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR_OF_DAY, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
return todayEnd.getTime();
}
/**
* 获取调整号 格式为 201812050001
* @return 返回组装好的调整号
*/
private String getAdjustNo(){
//获取当前日期
String code = DateUtil.getNowDate().replace("-","");
RedisAtomicLong entityIdCounter = new RedisAtomicLong(GOLD_ADJUST_RECORD_KEY, redisTemplate.getConnectionFactory());
//自增id
Long increment = entityIdCounter.incrementAndGet();
//设置过期时间为当天23:59:59:999
entityIdCounter.expireAt(DateUtil.getTodayEndTime());
if (increment < 10){
return code + "000" + increment;
} else if (increment < 100){
return code + "00" + increment;
}else if (increment < 1000){
return code + "0" + increment;
}else {
return code + increment;
}
}
简单方便实现带日期的自增单号 测试过没有并发问题