第一步 将库存数据写入redis列队
public function redislist()
{
$config = array(
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 10,
'password' => '123456',
'expire' => 10
);
$reids = new Redis($config);
$redis->ltrim('goods_store',1,0);
$store = 1000;
for($i = 0;$i < $store;$i++){
$redis->rPush('goods_store',$i+1);
}
$tol = $redis->llen('goods_store');
if($tol == $store){
echo '成功';
}else{
echo '失败';
}
exit;
}
第二步 开始抢购
public function tobuy()
{
$config = array(
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 10,
'password' => '123456',
'expire' => 10
);
$redis = new Redis($config);
$sid = $redis->lpop('goods_store');
if(!$sid){
echo '抢光了';
exit;
}
$orderid = $this->createoderid();
$arr = array('uid'=> mt_rand(100,9999),'money' => 10,'orderid' => $orderid,'goodid' => 1);
$status = false;
Db::startTrans();
try {
DB::name('order')->save($arr);
DB::name('goods_store')->where('id',5)->dec('num',1)->update();
Db::commit();
$status = true;
} catch (\Exception $e) {
Db::rollback();
}
if($status){
$num = $redis->llen('goods_store');
if($num <= 0){
echo '抢完了';
}else{
echo '抢到了';
}
}else{
$redis->rPush('goods_store',$sid);
}
exit;
}
public function createoderid($unique = null)
{
$orderNo = date('ymd').substr(microtime(), 2, 4) . mt_rand(1000,9999);
if(!empty($unique)) $orderNo = $orderNo.$unique;
return $orderNo;
}