package com.cloud.eagllwin.pay.common.util.id;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
@Service
public class IdGeberator {
@Autowired
private RedissonClient redissonClient;
/**
* redis key的层级不能超过3层()
* 根据前缀+日期+每天的自增编号例如(yyyyMMddHHmmssSSS00000001)
*
* @param key
* @param length
* @return
*/
public String getDayIncrCode(String key, int length) {
String formatDay = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
Long dayEndTime = getAppointDateTimeMills();
//当天失效
long liveTime = (dayEndTime - System.currentTimeMillis()) / 1000;
Long incre = getIncre(key+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")), liveTime);
String sequence = getSequence(incre, length);
return formatDay + sequence;
}
/**
* 获取指定时间毫秒值
*
* @return
*/
public static Long getAppointDateTimeMills() {
Calendar ca = Calendar.getInstance();
//失效的时间
ca.set(Calendar.HOUR_OF_DAY, 23);
ca.set(Calendar.MINUTE, 59);
ca.set(Calendar.SECOND, 59);
long curtime = ca.getTimeInMillis();
return curtime;
}
/**
* 获取redis原子自增数据
*
* @param key
* @param liveTime
* @return
*/
public Long getIncre(String key, long liveTime) {
RAtomicLong counter = null;
RBucket<Long> config = redissonClient.getBucket(key);
if (!config.isExists()) {
RLock lock = redissonClient.getLock(key);
try {
if (lock.tryLock()) {
counter=redissonClient.getAtomicLong(key);
}
} finally {
lock.unlock();
}
} else {
counter=redissonClient.getAtomicLong(key);
}
//初始设置过期时间
boolean result = (!counter.isExists()) && liveTime > 0;
if (result) {
counter.set(1);
counter.expire(liveTime, TimeUnit.SECONDS);
}
return counter.getAndIncrement();
}
/**
* 补全自增的数据
*
* @param seq
* @param length
* @return
*/
public static String getSequence(long seq, int length) {
String str = String.valueOf(seq);
int len = str.length();
// 取决于业务规模,应该不会到达4
if (len >= length) {
return str;
}
int rest = length - len;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rest; i++) {
sb.append('0');
}
sb.append(str);return sb.toString();
}
}
订单编号生成
于 2022-07-13 16:27:55 首次发布