yii框架redis结合php实现秒杀效果(实例代码)
程序员文章站
2022-05-30 20:52:47
废话不多说了,直接给大家贴代码了,具体代码如下所示:
废话不多说了,直接给大家贴代码了,具体代码如下所示:
<?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 "秒杀失败"; } } } ?>
总结
以上所述是小编给大家介绍的yii框架redis结合php实现秒杀效果(实例代码),希望对大家有所帮助