例子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方法,这样可以避免多次被实例化