package com.martin.utils;/* * @Author Martin·Antonio * @Description TODO * @DateTime 2022/11/18 21:06 * */ import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; @Component public class RedisIDGenerator { private static final long BEGIN_TIMESTAMP = 1640995200L; /** * 序列号的位数32 */ private static final long COUNT_BITS = 32; private StringRedisTemplate template; public RedisIDGenerator(StringRedisTemplate template) { this.template = template; } public long nextId(String keyPrefix) { //1.生成时间戳 LocalDateTime time = LocalDateTime.now(); long nowSecond = time.toEpochSecond(ZoneOffset.UTC); long timeStamp = nowSecond - BEGIN_TIMESTAMP; //2.生成序列号 //2.1获取当前日期,精确到天 String date = time.format(DateTimeFormatter.ofPattern("yyyy:MM:dd")); //2.2自增长 long count = template.opsForValue().increment("icr:" + keyPrefix + ":" + date); //3.拼接并返回 long l = timeStamp << COUNT_BITS | count; return l; } }
Reids 唯一性id生成工具类
最新推荐文章于 2024-05-30 08:41:13 发布