秒杀案例

package com.atguigu.seckill.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/seckill")
public class SecKController {
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public String test(){
        redisTemplate.opsForValue().set("name", "lucky");
        String name = (String)redisTemplate.opsForValue().get("name");
        System.out.println(name);
        return name;
    }

    //秒杀过程
    @GetMapping("/getThing")
    public boolean getThing(@RequestParam String prodid){
     String uid = new Random.nextInt(50000)+"";
        //1 uid和prodid非空判断
        if(uid == null || prodid == null){
            return  false;
        }

        //2、拼接key
        //2.1 秒杀库存key
        String kcKey = "sk:" + prodid +":qt";
        //2.2 秒杀成功用户key
        String userKey = "sk:" + prodid + ":user";
        //3 获取库存,如果库存null,秒杀没有开始
        Object kc = redisTemplate.opsForValue().get(kcKey);
        if(kc == null){
            System.out.println("秒杀还没开始,请等待");
            return false;
        }
        String kcnum = String.valueOf(kc);

        //4 判断用户是否重复秒杀操作
        if(redisTemplate.opsForSet().isMember(userKey, uid)){
            System.out.println("已经秒杀成功,不能重复秒杀");
            return  false;
        }
        //5 判断如果商品数量<=0,秒杀结束
        if(Integer.parseInt(kcnum)<=0){
            System.out.println("秒杀已结束");
            return  false;
        }
        //6 秒杀过程
        //6.1 秒杀到,库存减一
        redisTemplate.opsForValue().decrement(kcKey);
        //6.2 把秒杀成功用户添加到清单里面
        redisTemplate.opsForSet().add(userKey, uid);
        System.out.println("秒杀成功了");
        return true;
    }

}

 

posted @ 2023-06-04 10:20  佛系粥米  阅读(9)  评论(0编辑  收藏  举报