Redis中的队列list实现秒杀活动抢购
redis中的数据结构list中 rpush | lpop | lpush | rpop 实现队列的先进先出的特性
lpush:左边入队列,存入秒杀活动的商品
rpop:右边出队列,获取抢到的商品
1. 引入redis客户端maven依赖
<!-- java redis 客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
</dependency>
2. 定义抢购商品实体类
/**
* @description
* 商品货物
* @author TianwYam
* @date 2021年10月24日下午6:33:17
*/
@Data
@Builder
public class Goods {
// 商品编号
private int goodsId ;
// 商品名称
private String goodsName ;
// 价格
private double price ;
}
3. 定义模拟用户抢购线程类
/**
* @description
* 用户抢购线程
* @author TianwYam
* @date 2021年10月25日下午1:22:09
*/
public class PersonShoppingThread implements Runnable{
public static final String LIST_GOODS = "LIST_GOODS";
// 顺序
private int index ;
// 用户姓名
private String name ;
private Jedis jedis ;
public PersonShoppingThread(int index, Jedis jedis) {
this.index = index ;
this.jedis = jedis ;
this.name = new Faker(Locale.SIMPLIFIED_CHINESE).name().fullName();
}
@Override
public void run() {
// 模拟 用户抢购 耗时
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 获取 秒杀商品队列 数量
Long len = jedis.llen(LIST_GOODS);
if (len == null || len <= 0) {
System.out.println(String.format