电商秒杀-利用 Redis 队列操作的原子性实现秒杀

商品限时抢购,秒杀的玩法在电商领域应用广泛,是一种有效的提升流量,消耗库存的举措。

如何高效的处理比并发操作实现秒杀功能呢 

废话不多说 上代码,

新手上路 大神勿喷

 

1.添加一个队列模拟商品列表

    public static void main(String[] args)  throws  Exception{
        // redis的队列操作是原子操作
        // eg: 30个人抢10个商品
        // lpush productlist 1 2 3 4 5 6 7 8 9 10 商品ID号
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMaxWaitMillis(10000);
        jedisPoolConfig.setMaxTotal(1024);

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 7856);

        Jedis resource = jedisPool.getResource();
        resource.select(0);
        resource.del("productlist");
        String[] list={"商品1","商品2","商品3","商品4"};
        resource.lpush("productlist",list);
        resource.close();

    }

 2.利用多线程模拟 30 个人抢购这 10 件商品:

 public static void main(String[] args) {
        // redis的队列操作是原子操作
        // eg: 30个人抢10个商品
        // lpush productlist 1 2 3 4 5 6 7 8 9 10 商品ID号
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMaxWaitMillis(10000);
        jedisPoolConfig.setMaxTotal(1024);
        
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
        
        ExecutorService executor = Executors.newFixedThreadPool(30);
        
        for (int i = 0; i < 30; i++) {
            executor.execute(new SpikeTask(i, jedisPool));
        }
  
        executor.shutdown();
    }

class SpikeTask implements Runnable {

    private int customerId;
    
    private JedisPool jedisPool;
    
    public SpikeTask (int customerId, JedisPool jedisPool) {
        this.customerId = customerId;
        this.jedisPool = jedisPool;
    }
    
    @Override
    public void run() {
        
        // 执行秒杀
        Jedis client = jedisPool.getResource();
        
        String productId = client.lpop("productlist");
        
        if (productId != null && productId.length() != 0) {
            System.out.println("顾客" + customerId + "抢到了" + productId + "号商品");
        } else {
            System.out.println("顾客" + customerId + "没有抢到商品");
        }
        
    }
}

3 秒杀结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值