利用 Redis 队列操作的原子性实现秒杀
1.添加一个队列模拟商品列表 启动redis 输入 lpush str 1 2 3 4 5 6 7 8 9 10
2.利用多线程模拟 20 个人抢购这 10 件商品:
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: 20个人抢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); //或者java代码lpush进去 //String str[]= {"1","2","3","4","5","6","7","8","9","10"}; //Jedis client = jedisPool.getResource(); //client.lpush("str",str ); ExecutorService executor = Executors.newFixedThreadPool(30); for (int i = 0; i < 20; 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("str"); if (productId != null && productId.length() != 0) { System.out.println("顾客" + customerId + "抢到了" + productId + "号商品"); } else { System.out.println("顾客" + customerId + "没有抢到商品"); } } }
3.秒杀结果:
相关推荐
王道革 2020-11-25
wangdonghello 2020-11-03
Langeldep 2020-11-16
chenhualong0 2020-11-16
聚合室 2020-11-16
koushr 2020-11-12
MRFENGG 2020-11-11
guoyanga 2020-11-10
fackyou00 2020-11-10
Orangesss 2020-11-03
dongCSDN 2020-10-31
rainandtear 2020-10-30
Quietboy 2020-10-30
liuyulong 2020-10-29
fansili 2020-10-29
温攀峰 2020-10-23
jackbon 2020-10-19
kaixinfelix 2020-10-04