import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Component
public class PrimaryGenerator {
@Autowired
private RedisTemplate redisTemplate;
/**
* redis任务流水号key
*/
private final static String REDIS_TASK_KEY = "serial";
private final static String TASK_PREFIX = "T";
public synchronized String createTaskNo(int codeLength) {
String dateStr = getDateStr();
String key = REDIS_TASK_KEY + dateStr;
String noPrefix = TASK_PREFIX + dateStr;
Long count = redisTemplate.opsForValue().increment(key, 1);
redisTemplate.boundValueOps(key).expire(1, TimeUnit.DAYS);
String code = addZeroForNum(count.toString(), codeLength - noPrefix.length());
// 最终结果
return noPrefix + code;
}
private String getDateStr() {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
return formatter.format(date);
}
private String addZeroForNum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
sb.append("0").append(str);// 左补0
str = sb.toString();
strLen = str.length();
}
}
return str;
}
}