zoukankan      html  css  js  c++  java
  • 利用 Redis 队列操作的原子性实现秒杀

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

    lpush productlist 1 2 3 4 5 6 7 8 9 10
    1
    利用多线程模拟 30 个人抢购这 10 件商品:

    package demo;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    /**
    * @author qujianlei
    * @date 2019年1月5日 下午2:49:11
    * @description 通过Redis队列的原子操作实现秒杀
    */
    public class RedisSpike {
    
    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 + "没有抢到商品");
    }
    
    }
    }

    参考文章:https://blog.csdn.net/a909301740/article/details/85853414

  • 相关阅读:
    Android View 阴影的总结
    清晰的教你如何将 Maven 项目上传至 中央仓库以及版本更新
    简单粗暴的上传项目至 Github
    App自动更新(DownloadManager下载器)
    类型判断
    前端防御XSS
    window.location.href/replace/reload()/页面跳转+替换+刷新
    对数组排序进行"洗牌"(随机排序)
    iframe跨域上传图片
    Vim 新手节省时间的小技巧
  • 原文地址:https://www.cnblogs.com/faker2014/p/10848941.html
Copyright © 2011-2022 走看看