java——redis随笔——实战——优惠券秒杀

发布时间 2023-10-28 13:19:28作者: 小白龙白龙马

黑马视频地址:https://www.bilibili.com/video/BV1cr4y1671t?p=49&spm_id_from=pageDriver&vd_source=79bbd5b76bfd74c2ef1501653cee29d6

 

csdn地址:https://blog.csdn.net/weixin_50523986/article/details/131815165

 

 

 

 

 

 

 

 

 

 

  • stringRedisTemplate.opsForValue().increment函数:

 

package com.hmdp.utils;

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;

@Component
public class RedisIdWorker {

    // 定义一个初始时间戳
    public static final long BEGIN_TIME = 1640995200L;

    // 序列号位数
    public static final long COUNT_BITS = 32;

    // 用到redis的自增长
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix){

        // 1 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIME;

        // 2 生成序列号
        // 确定当天序列号的key 获取当天日期 精确到天
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:DD"));
        // 实现自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + data);

        // 3 拼接并返回  借助位运算
        // 移位之后后面32位全都是0 或运算可以保证原来的样子
        return timeStamp << COUNT_BITS | count;

    }

    public static void main(String[] args) {
//        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
//        long timeToSecond = time.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(timeToSecond);

    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1

1

1