這篇文章主要介紹了關於Redis簡單一實例,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
<?php/** * Created by PhpStorm. * User: Perilla * Date: 2018/4/27 * Time: 9:13 */namespace app\index\controller;/** * Class Reids * 作用:學習redis * 時間:2018年4月27日15:07:28 * (基礎已遷移到extend/Reids) * * * 隊列的rPop是具有原子性的,即使處理並發,也是一個個處理,不會出現重複和超賣的情況 * Set的特性是不能重複 * 使用者搶購隊列(List) * 商品隊列(List) * 訂單資訊(Hash集合) * 購買成功使用者(Set集合) */class Reids{ private $reids; /** * 初始化一個reids */ public function __construct(\Redis $reids){ header("content-type:text/html;charset=utf-8"); $this->reids = $reids; $this->reids->connect('127.0.0.1',6379); if($this->reids->ping() == "+PONG"){ echo "reids 正常運行<br/>".PHP_EOL; }else{ echo "reids 開啟失敗<br/>".PHP_EOL; } } /** * 建立一個貨物庫 貨物n個 */ public function goods($n){ $this->reids->delete('goodsLists'); $this->reids->delete('killsLists'); $this->reids->delete('ordersLists'); $this->reids->delete('usersLists'); for($i = 1;$i<=$n;$i++){ $this->reids->lpush('goodsLists',$i); } echo '進貨成功,商品數:'.$this->reids->lsize('goodsLists'); } public function getkillsLists(){ $count = $this->reids->scard('killsLists'); $this->dumps("購買數量",$count); $arr = $this->reids->smembers('killsLists'); $this->dumps("購買清單",$arr); $length = $this->reids->lsize('goodsLists'); $this->dumps("商品剩餘數量:",$length); $arr = $this->reids->hgetall('ordersLists'); $this->dumps("商品購買詳情:",$arr); } /** * 秒殺過程 * usersLists 使用者表(List) * goodsLists 貨物表(List) * killsLists 秒殺成功表(Set集合) * ordersLists 訂單表(Hash集合) */ public function kills(){ //查詢庫存 if($this->reids->lLen('goodsLists') == 0) { $this->dumps("商品已售完..."); exit; } //查詢是否購買過 $uid = rand(100000,999999); if($this->reids->sIsMember('killsLists',$uid)){ $this->dumps('你已經購買過了!'); exit; } //購買 $goods_id = $this->reids->rpop('goodsLists'); if($goods_id){ $this->reids->sAdd('killsLists',$uid); $value = array( 'uid' => $uid, 'goods_id' => $goods_id, 'time' => time(), ); $this->reids->hSet('ordersLists',$uid,json_encode($value)); $this->dumps('購買成功。'); } } /** * 按一定規律列印一些資料 */ public function dumps($demo,$val = ""){ echo $demo.PHP_EOL; if($val){ dump($val); } echo PHP_EOL; }}