public class IdSeqGenerator { /** * 昵称计数器,确保唯一性 */ private static final String ID_COUNTER_REDISKEY = "ID_COUNTER:"; /** * ID前缀 */ private static final String NICKNAME_PREFIX = "2017"; /** * 日期起始点 */ private final static long epoch = 1463108596098L; @Autowired private JedisPool jedisPool; /** * 初始化redis计数器从 100000000 开始 */ @PostConstruct private void init() { try (Jedis jedis = jedisPool.getResource()) { if (jedis.get(ID_COUNTER_REDISKEY) == null) { jedis.set(ID_COUNTER_REDISKEY, "100000000"); } } } public String generate() { try (Jedis jedis = jedisPool.getResource()) { // 起始时间到当前时间的分钟数作为随机因子, 用来减少全是1个数的出现情况 long value = (System.currentTimeMillis() - epoch) / 60000 + jedis.incr(ID_COUNTER_REDISKEY); return NICKNAME_PREFIX + String.valueOf(value); } } }
redis ID生成器
最新推荐文章于 2024-10-07 08:55:38 发布