例子redis做秒殺和其它功能(避免被多次實例化)
<?php
namespace app\index\controller;
class Base extends \think\Controller
{
// 實例
protected static $reids = null;
public static function getRedis(){
if(null === self::$reids) {
self::$reids = new \Redis();
self::$reids->connect('127.0.0.1',6379);
self::$reids->auth('123456');
}
return self::$reids;
}
}
<?php
namespace app\index\controller;
use think\Db;
class Index extends Base
{
public function index()
{
$mobile='17805990428'.rand(0,19); //用戶
Db::startTrans();
try{
$inventory_value = Db::name('inventory')->where('id',1)->lock(true)->find();//行鎖
if($inventory_value['number_value'] == 0 && $inventory_value['number_value'] == ''){
Db::rollback();
return $this->msg('20000','秒殺結束','');
}
self::getRedis()->rpush("mobile",$mobile); //隊列
//做秒殺邏輯
Db::name('inventory')->where('id',1)->setDec('number_value',1);
$seckill = [
'userID' => $mobile,
'create_time' => date('Y-m-d H:i:s',time())
];
Db::name('seckill')->insert($seckill);
self::getRedis()->lpop('mobile'); //清空
// 提交事務
Db::commit();
} catch (\Exception $e) {
// 回滾事務
Db::rollback();
return $this->msg('20000','秒殺已結束','');
}
}
}
使用redis都去調用getRedis方法,這樣可以避免多次被實例化