秒杀demo

简单的秒杀demo,使用redis缓存令牌和库存,可水平扩展

 

@RequestMapping(name = "/seckill", method = RequestMethod.POST)
    public String seckill(){
        RedisAtomicLong stockAtomic = new RedisAtomicLong(test_stock, redisTemplate.getConnectionFactory());

        // 判断库存
        if (stockAtomic.get() < 1) {
            return "10";
        }
        RedisAtomicLong tokenAtomic = new RedisAtomicLong(test_token, redisTemplate.getConnectionFactory());
        try {
            // 令牌-限流
            if (tokenAtomic.decrementAndGet() < 0) {
                return "20";
            }
            Thread.sleep(new Random().nextInt(2000));

            // 减库存
            if (stockAtomic.decrementAndGet() < 0) {
                stockAtomic.incrementAndGet();
                return "11";
            }



            // 异常更新库

        } catch (Exception e) {
            e.printStackTrace();
//            stockAtomic.addAndGet(1);
        } finally {
            // 释放令牌
            tokenAtomic.incrementAndGet();
        }

        return "30";
    }

 

你可能感兴趣的:(秒杀demo)