redis实现全局唯一id
java
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Component
public class RedisIdWorker {
private StringRedisTemplate stringRedisTemplate;
private static final long BEGIN_TIMESTAMP = 1640995200L;
private static final int COUNT_BITS = 32;
public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
public long nextId(String keyPrefix){
// 生成时间戳
LocalDateTime now = LocalDateTime.now();
long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
long timestamp = nowSecond - BEGIN_TIMESTAMP;
// 生成序列号
String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
return timestamp << COUNT_BITS | count;
}
}
timestamp << COUNT_BITS | count
:
将timestamp 向左移动32位,再和count做或运算
- 获取指定日期的时间戳
java
@Test
void test() throws Exception{
LocalDateTime dateTime = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
long epochSecond = dateTime.toEpochSecond(ZoneOffset.UTC);
System.out.println("epochSecond = " + epochSecond);
}
- 其他全局ID生成策略
- UUID
- redis自增
- 雪花算法
- 数据库自增 (单独一张自增表)