今天尝试写并发抢购功能,再网上找了相关资料后,实现了如下:
<?php
#开始抢购,检测库存
$inventoryData = $this->redis->get($inventoryKey);
if ($inventoryData == null) {
//库存不足
return '-1';
}
#解析json
$inventoryData = json_decode($inventoryData, true);
#检测库存
if ($inventoryData['inventory'] == 0) {
//库存不足
return '-1';
}
//开启事务
$this->redis->watch($inventoryKey);
//事务开始
$this->redis->multi();
//将抢购数据加入redis
$this->redis->lPush('kill_goods_' . $data['goods_id'], json_encode($data));
$goodsData = ['id' => $data['goods_id'], 'inventory' => $inventoryData['inventory'] - 1];
$this->redis->set($inventoryKey, json_encode($goodsData));
$result = $this->redis->exec();
if ($result) {
file_put_contents('1.txt', $inventoryData['inventory'] . PHP_EOL, FILE_APPEND);
return 1;
}
return '-1';
经过并发测试:始终都会有重复的,请各位大佬讲解讲解
撒科打诨
GCT1015
qq_花开花谢_0