feat: 根据redis产生自增id
原因
根据redis产生自增id
修改
根据redis产生自增id
This commit is contained in:
parent
906337ddc9
commit
e3c209d15e
@ -0,0 +1,57 @@
|
||||
package cn.axzo.foundation.redis.support;
|
||||
|
||||
import cn.axzo.foundation.web.support.AppRuntime;
|
||||
import cn.axzo.foundation.web.support.utils.KeyBuilder;
|
||||
import lombok.Builder;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* https://blog.csdn.net/m0_54189068/article/details/131546812
|
||||
*/
|
||||
public class RedisIdWorker {
|
||||
|
||||
private static final long BEGIN_TIMESTAMP = 1640995200L;
|
||||
private static final long COUNT_BITS = 32;
|
||||
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
private RedisTemplate redisTemplate;
|
||||
private AppRuntime appRuntime;
|
||||
|
||||
@Builder
|
||||
public RedisIdWorker(RedisTemplate redisTemplate, AppRuntime appRuntime) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.appRuntime = appRuntime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据时间+redis产生全唯一键
|
||||
*/
|
||||
public long nextId(String prefix) {
|
||||
// 1.生成全局ID时间戳部分
|
||||
LocalDateTime date = LocalDateTime.now();
|
||||
long nowSecond = date.toEpochSecond(ZoneOffset.UTC);
|
||||
long timestamp = nowSecond - BEGIN_TIMESTAMP;
|
||||
|
||||
// 2.生成全局ID序列号部分
|
||||
// 2.1获取当前日期,精确到天
|
||||
// 2.2获取自增长值
|
||||
Long count = getDailyNextId(prefix, date.toLocalDate());
|
||||
|
||||
// 3.拼接时间戳和序列号并返回
|
||||
return timestamp << COUNT_BITS | count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据时间+redis产生当天自增id
|
||||
*/
|
||||
public long getDailyNextId(String prefix, LocalDate date) {
|
||||
String key = KeyBuilder.build(appRuntime, prefix, "icr", DATE_TIME_FORMATTER.format(date));
|
||||
Long count = redisTemplate.opsForValue().increment(key);
|
||||
return count;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user