parent
520bcd8320
commit
a6ee47947c
@ -0,0 +1,52 @@
|
||||
package util;
|
||||
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @Author: yawei.huang
|
||||
* @Package: util
|
||||
* @Project: luoo_parent
|
||||
* @Date: 2024/5/30 8:34
|
||||
* @Filename: RedisLockUtil
|
||||
* @Describe:
|
||||
*/
|
||||
@Component
|
||||
public class RedisLockUtil {
|
||||
|
||||
@Resource
|
||||
private RedisTemplate<String, String> redisTemplate;
|
||||
|
||||
private static final String KEY_PREFIX = "serial_number:";
|
||||
private static final String DATE_FORMAT = "yyMMdd";
|
||||
|
||||
public String generateSerialNumber() {
|
||||
String key = KEY_PREFIX + getCurrentDate();
|
||||
Long increment = redisTemplate.opsForValue().increment(key, 1);
|
||||
if (increment == 1) {
|
||||
redisTemplate.expire(key, getSecondsUntilEndOfDay(), TimeUnit.SECONDS);
|
||||
}
|
||||
return getCurrentDate() + String.format("%04d", increment);
|
||||
}
|
||||
|
||||
private String getCurrentDate() {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
|
||||
return sdf.format(new Date());
|
||||
}
|
||||
|
||||
private long getSecondsUntilEndOfDay() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime endOfDay = now.with(LocalTime.MAX);
|
||||
Duration duration = Duration.between(now, endOfDay);
|
||||
return duration.getSeconds();
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in new issue