
package com.hmdp.utils;
import org.springframework.beans.factory.annotation.Autowired;
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 static final long BEGIN_TIMESTAMP = 1762300800L;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public long nextId(String keyPrefix){
LocalDateTime now = LocalDateTime.now();
long second = now.toEpochSecond(ZoneOffset.UTC);
long timestamp = second - BEGIN_TIMESTAMP;
String yyyyMMdd = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
long count = stringRedisTemplate.opsForValue().increment(keyPrefix + ":" + yyyyMMdd);
return timestamp << 32 | count;
}
}