当前位置: 首页 > 科技观察

Redis秒杀实现方案详解

时间:2023-03-17 12:51:48 科技观察

1.全局唯一ID(1)定义一个全局ID生成器,它是分布式系统中用来生成全局唯一ID的工具,一半满足以下特性:唯一性、高可用、高性能、增量安全,在为了增加ID的安全性,为了安全,我们没有直接使用Redis的自增值,而是拼接了一些其他信息。ID的组成部分:符号位:1bit,一直为0时间戳:31bit,单位秒,可以使用69年序列号:32bit,秒内计数,支持每秒2?32个不同的ID(二)代码实现@ComponentpublicclassRedisIdWorker{/***开始时间戳*/privatestaticfinallongBEGIN_TIMESTAMP=1640995200L;/***序列号的位数*/privatestaticfinalintCOUNT_BITS=32;@AutowiredprivateStringRedisTemplatestringRedisTemplate;publiclongnextId(StringkeyPrefix){//1.生成时间戳LocalDateTimenow=LocalDateTime.now();longnowSecond=now.toEpochSecond(ZoneOffset.UTC);长时间戳=nowSecond-BEGIN_TIMESTAMP;//2.生成流水号//2.1.获取当前日期,精确到天Stringdate=now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));//2.2。自增长longcount=stringRedisTemplate.opsForValue().increment("icr:"+keyPrefix+":"+date);//3.拼接返回returntimestamp<