Created
May 10, 2024 07:32
-
-
Save JoJoJotarou/655d33d4d0f690c4136865a366ee51e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 通过redis自增key获取全局唯一ID,每天重置 | |
public String getUniqueId(String key) { | |
RedisScript<Long> luaScript = new DefaultRedisScript<>( | |
"local exists = redis.call('EXISTS', KEYS[1])\n" + | |
"if exists == 0 then\n" + | |
" redis.call('INCR', KEYS[1])\n" + | |
" redis.call('PEXPIRE', KEYS[1], ARGV[1])\n" + | |
" return tonumber(1)\n" + | |
"else\n" + | |
" return tonumber(redis.call('INCR', KEYS[1]))\n" + | |
"end", Long.class); | |
LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0); | |
Integer millSeconds = Math.toIntExact(ChronoUnit.MILLIS.between(LocalDateTime.now(), midnight)); | |
Long id = (Long) redisTemplate.execute(luaScript, Collections.singletonList(key), millSeconds); | |
return String.format("%08d", id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment