直接利用redis的incrBy
即可。
private String getNewTaskNo() {
String today = DateTimeUtil.dateToStr(new Date(), "yyyyMMdd");
Long newNo = redisUtil.incrBy(today, 1);
redisUtil.expire(today, 3600 * 24);
return today + "-" + newNo;
}
如果要精确控制expire的time,则可以使用
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 24);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
int lockTime = (int) ((calendar.getTimeInMillis() - System.currentTimeMillis()) / 1000);
如果要前面填充一个0,则:
private String getNewTaskNo() {
String today = DateTimeUtil.dateToStr(new Date(), "yyyyMMdd");
Long newNo = redisUtil.incrBy(today, 1);
redisUtil.expire(today, 3600 * 24);
if (newNo < 10) {
return today + "-" + "0" + newNo;
}
return today + "-" + newNo;
}