首页 > 开发 > PHP > 正文

yii框架redis结合php实现秒杀效果(实例代码)

2024-05-04 21:50:08
字体:
来源:转载
供稿:网友

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

  1. <?php 
  2. namespace backend/controllers; 
  3. use Yii; 
  4. use yii/web/Controller; 
  5. /** 
  6.  
  7. */ 
  8. class GoodsController extends Controller 
  9. public $enableCsrfValidation=false; 
  10. public function actionInfo() 
  11. $data=yii::$app->db->createCommand("select * from goods ")->queryAll(); 
  12. return $this->render('index',['data'=>$data]); 
  13. Public function actionXx() 
  14. $id=yii::$app->request->get('id'); 
  15. $data=yii::$app->db->createCommand("select * from goods where id='$id'")->queryOne(); 
  16. return $this->render('info',['data'=>$data]); 
  17. Public function actionAdd() 
  18. $a=yii::$app->redis; 
  19. if (Yii::$app->request->isPost) 
  20. $data=yii::$app->request->post(); 
  21. $res=yii::$app->db->createCommand()->insert('goods',$data)->execute(); 
  22. if($res
  23. for ($i=0; $i <$data['counts'] ; $i++) 
  24. {  
  25. $a->lpush('goods',1); 
  26. return $this->redirect(array('goods/info')); 
  27. else 
  28. echo "添加失败"
  29. else 
  30. return $this->render('add'); 
  31. public function actionOrder() 
  32. $redis=yii::$app->redis; 
  33. $count=$redis->lpop('goods'); 
  34. if(emptyempty($count)) 
  35. echo "库存不足";die
  36. $res=yii::$app->db->createCommand("update goods set counts=counts-1 where id=1 and counts>0")->execute(); 
  37. if($res//Vevb.com 
  38. echo "秒杀成功"
  39. else 
  40. echo "秒杀失败"
  41. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表