<?php
/*-------------------------------------------------
* redis驱动类,需要安装phpredis扩展
*
* @athor liubin
* @link http://pecl.php.net/package/redis
* @date 2016-02-09
*-------------------------------------------------
*/
class QRedis{
private $_redis = null;
/** 构造**/
public function __construct(){
if($this->_redis === null){
try{
$redis = new Redis();
$hanedel = $redis->connect('127.0.0.1',6379);
if($hanedel){
$this->_redis = $redis;
}else{
echo 'redis服务器无法链接';
$this->_redis = false;
exit;
}
}catch(RedisException $e){
echo 'phpRedis扩展没有安装:' . $e->getMessage();
exit;
}
}
}
/** 队列尾追加**/
public function addRlist($key,$value){
$result = $this->_redis->rPush($key,$value);
return $result;
}
/** 队列头追**/
public function addLlist($key,$value){
$result = $this->_redis->lPush($key,$value);
return $result;
}
/** 头出队列**/
public function lpoplist($key){
$result=$this->_redis->lPop($key);
return $result;
}
/** 尾出队列**/
public function rpoplist($key){
$result=$this->_redis->rPop($key);
return $result;
}
/** 查看队列**/
public function showlist($key){
$result = $this->_redis->lRange($key, 0, -1);
return $result;
}
/** 队列数量**/
public function listcount($key){
$result = $this->_redis->lSize($key);
return $result;
}
/** 清空队列**/
public function clearlist($key){
$result = $this->_redis->delete($key);
return $result;
}
/** 获取redis资源对象**/
public function getHandel(){
return $this->_redis;
}
}
?>
以上是建立redis链接,下面是实现库存减少(简单案例实现)
/*
* 基于redis队列验证库存信息
* @desc Redis是底层是单线程的,命令执行是原子操作,包括lpush,lpop等.高并发下不会导致超卖
*/
protected function order_check_redis($gid){
$goodsInfo = $this->_goodsModel->getGoods($gid);
if(!$goodsInfo){
$this->_error = '商品不存在';
return false;
}
$key = 'goods_list_'.$goodsInfo['id'];
$count = $this->_redis->getHandel()->lpop($key);
if(!$count){
$this->_error = '库存不足';
return false;
}
//生成订单
$data = [];
$data['order_id'] = $this->_orderModel->buildOrderNo();
$data['goods_id'] = $goodsInfo['id'];
$data['addtime'] = time();
$data['uid'] = 1;
$order_rs = $this->_orderModel->create_order($data);
//库存减少
$gid = $goodsInfo['id'];
$sql = 'UPDATE goods SET counts = counts - 1 WHERE id = '.$gid;
$result = $this->_goodsModel->exect($sql);
$this->_error = '购买成功';
return true;
}