全局id生成器,是一种在分布式系统下用来生成全局唯一id的工具,一般满足下列特性:
唯一性:确保id是唯一的,不可重复
递增性:确保是整体逐渐增大的,这样有利于数据库创建索引
安全性:id的规律性不是特别的明显,防止根据id号猜测其他的id,确保安全性
高性能:确保生成id的速度足够快
高可用:确保任何时候都能用
实现原理:为了提高id的安全性,可以采用将redis自增数值与其他信息进行拼接的方式来组成id,具体组成方式如图所示:
符号位:1bit,永远为0,表示正数
时间戳:31bit,以秒为单位,可以使用大约69年
序列号:32bit,相同秒数的情况下,id在序列号位置上增加,支持每秒产生2^32个不同的id
代码实现:
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; @componentpublic class redisidworker { /** * 开始时间戳 (2022-01-01 00:00:00) */ private static final long begin_timestamp = 1640995200l; /** * 序列号的位数 */ private static final int count_bits = 32; @autowired private stringredistemplate stringredistemplate; /** * 生成id * * @param keyprefix 业务系统的前缀 * @return id */ public long nextid(string keyprefix) { // 生成时间戳 long timestamp = localdatetime.now().toepochsecond(zoneoffset.utc) - begin_timestamp; // 生成序列号 string key = "icr:" + keyprefix + ":" + localdatetime.now().format(datetimeformatter.ofpattern("yyyy:mm:dd")); long count = stringredistemplate.opsforvalue().increment(key); // 拼接并返回 return timestamp << count_bits | count; } /** * 获取时间戳 (2022-01-01 00:00:00) * @param args */ public static void main(string[] args) { localdatetime time = localdatetime.of(2022, 1, 1, 0, 0, 0); long second = time.toepochsecond(zoneoffset.utc); system.out.println(second); }}
生成序号:
redis的自增是有上限的,最大值为2^64。尽管这个数字很大,但毕竟有一个上限,如果时间足够长,仍有可能超过这个数字。所以即使是同一个业务,也不能使用同一个key。因此可以在key中增加日期,比如:icr:业务名:2022:05:14。以这种方式生成的键每天都会是一个新的键,每天的自增量不会超过2^64,因此这样的键是一个比较合适的选择。
以上就是redis全局id生成器如何实现的详细内容。