redis秒杀

package com.test.springdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

@RestController
public class OrderController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping(value = "purchase/{productId}")
    public boolean purchase(@PathVariable("productId") String productId) {
    /*    redisTemplate.opsForZSet().add("zset","1",0.1);
        redisTemplate.opsForZSet().add("zset","2",0.2);
        Set<ZSetOperations.TypedTuple<String>> zet = redisTemplate.opsForZSet().rangeWithScores("zset1", 0, -1);
        Iterator<ZSetOperations.TypedTuple<String>> iterator = zet.iterator();
        while (iterator.hasNext()){
            ZSetOperations.TypedTuple<String> next = iterator.next();
            System.out.println(next.getValue());
        }*/
        if (productId==null) return false;

        long orderNum = System.currentTimeMillis();

        //判断该订单号是否已经成功下单
        boolean temp = redisTemplate.opsForSet().isMember("orderNum",orderNum+"");
        if (temp) return true;

        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.watch("product:"+productId);

        String productNum = redisTemplate.opsForValue().get("product:"+productId);
        if(null==productNum ) {return false;}
        long num = Long.valueOf(productNum );
        //获取当前商品的数量
        if (num<=0){
            //检查当前商品的数量
            redisTemplate.opsForList().leftPush("state","订单号="+orderNum+"----商品编号="+productId+"----秒杀已结束");
            return false;
        }
        redisTemplate.multi();//事务
        redisTemplate.boundValueOps("product:"+productId).decrement(1);
        redisTemplate.opsForSet().add("orderNumber",orderNum+"");
        List<Object> exec = redisTemplate.exec();
        if (exec==null||exec.size()==0){
            redisTemplate.opsForList().rightPush("state","订单号="+orderNum+"----商品编号="+productId+"----秒杀失败");
            return false;
        }else{
            redisTemplate.opsForList().rightPush("state","订单号="+orderNum+"----商品编号="+productId+"----秒杀成功");
            return true;//成功秒杀商品
        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值