首页 >后端开发 >php教程 >Yii框架redis+php实现秒杀效果的实例分析

Yii框架redis+php实现秒杀效果的实例分析

黄舟
黄舟原创
2017-10-27 09:09:361516浏览

废话不多说了,直接给大家贴代码了,具体代码如下所示:

<?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(&#39;index&#39;,[&#39;data&#39;=>$data]);
}
Public function actionXx()
{
$id=yii::$app->request->get(&#39;id&#39;);
$data=yii::$app->db->createCommand("select * from goods where id=&#39;$id&#39;")->queryOne();
return $this->render(&#39;info&#39;,[&#39;data&#39;=>$data]);
}
Public function actionAdd()
{
$a=yii::$app->redis;
if (Yii::$app->request->isPost)
{
$data=yii::$app->request->post();
$res=yii::$app->db->createCommand()->insert(&#39;goods&#39;,$data)->execute();
if($res)
{
for ($i=0; $i <$data[&#39;counts&#39;] ; $i++)
{ 
$a->lpush(&#39;goods&#39;,1);
}
return $this->redirect(array(&#39;goods/info&#39;));
}
else
{
echo "添加失败";
}
}
else
{
return $this->render(&#39;add&#39;);
}
}
public function actionOrder()
{
$redis=yii::$app->redis;
$count=$redis->lpop(&#39;goods&#39;);
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实现秒杀效果的实例分析的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn