Home  >  Article  >  Backend Development  >  Example analysis of Yii framework redis+php to achieve flash sale effect

Example analysis of Yii framework redis+php to achieve flash sale effect

黄舟
黄舟Original
2017-10-27 09:09:361488browse

Without further ado, I will post the code directly for you. The specific code is as follows:

<?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 "秒杀失败";
}
}
}
?>

The above is the detailed content of Example analysis of Yii framework redis+php to achieve flash sale effect. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn