yii框架redis结合php实现秒杀效果(实例代码)
废话不多说了,直接给大家贴代码了,具体代码如下所示:
<?php namespace backend\controllers; use Yii; use yii\web\Controller; /** * */ class GoodsController extends Controller { public $enableCsrfValidation=false; public function actionInfo() { $data=yii::$app->db->createCommand("select * from goods ")->queryAll(); return $this->render('index',['data'=>$data]); } Public function actionXx() { $id=yii::$app->request->get('id'); $data=yii::$app->db->createCommand("select * from goods where id='$id'")->queryOne(); return $this->render('info',['data'=>$data]); } Public function actionAdd() { $a=yii::$app->redis; if (Yii::$app->request->isPost) { $data=yii::$app->request->post(); $res=yii::$app->db->createCommand()->insert('goods',$data)->execute(); if($res) { for ($i=0; $i <$data['counts'] ; $i++) { $a->lpush('goods',1); } return $this->redirect(array('goods/info')); } else { echo "添加失败"; } } else { return $this->render('add'); } } public function actionOrder() { $redis=yii::$app->redis; $count=$redis->lpop('goods'); if(empty($count)) { echo "库存不足";die; } $res=yii::$app->db->createCommand("update goods set counts=counts-1 where id=1 and counts>0")->execute(); if($res) { echo "秒杀成功"; } else { echo "秒杀失败"; } } } ?>
总结
相关推荐
wmsjlihuan 2020-04-26
igogo00 2020-03-09
WasteLand 2020-10-18
Allinputs 2020-08-30
Ashes 2020-06-14
caiyiii 2020-06-14
kxguan 2020-06-14
daillo 2020-06-14
一粒沙里的世界 2020-06-14
ruxingli 2020-06-14
csssy00 2020-06-14
阿佐 2020-06-14
NameWFY 2020-05-28
NameWFY 2020-05-26
Robin罗兵 2020-05-16
caiyiii 2020-04-29
cbao 2020-04-26
csssy00 2020-04-19