thinkphp5使用redis分布式锁来实现抢购

redis利用分布式锁来实现抢购

```
//do {
$timeout = 10;
$processid = rand(1, 100000).rand(1, 100000);
$key = 'process_lock';
$value = 'process_'.$processid;
$isLock = Cache::store('redis')->rawCommand('set',$key, $value,"EX",$timeout,"NX");
if ($isLock) {
$is_check = Db::name('goods_order')->where('goods_id', 1)->where('username', '1381646')->count();
if ($is_check >= 10) {
echo '该团已结束!';
if (Cache::store('redis')->rawCommand('get',$key) == $value) {
Cache::store('redis')->del($key);
}
exit;
}
$time = time();
$sql = "INSERT INTO `goods_order` ( `sid`, `order_sn`, `username`, `goods_id`) VALUES (1, '20220123180655265788', '1381646', 1);
";
Db::name('goods_order')->execute($sql);

//秒杀成功
Db::name('goods_list')->where('id', 1)->setInc('sold_number');
Db::name('goods_list')->where('id', 1)->setDec('goods_number');

if (Cache::store('redis')->rawCommand('get',$key) == $value) {
Cache::store('redis')->del($key);
//continue;
}
echo "yes";
}else{
echo "no";
}
// } else {
// usleep(5000);
// }
// } while(!$isLock);
```

    A+
发布日期:2022年01月25日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: