app里要做个限时秒杀的功能,抢购优惠券的,代码如下:
限时秒杀的主界面代码:
public function miaoSha(){ //限时秒杀
date_default_timezone_set("Asia/Shanghai");
if(date('G')>14 && date('G')<16){ //秒杀活动是下午3点钟
$this -> assign('data',1); //活动开始
}else{
$this -> assign('data',0);
}
$phone = Session::get('phone');
$redis = new \Redis();
$redis -> connect('127.0.0.1',6379);
if($redis->hget('status',$phone)){ //如果用户抢购成功了,那么就不可以重复抢购了
$this -> assign('data',2);
}
return $this -> fetch('miaoSha');
}
redis消息队列代码:
public function seckill(){ //秒杀 ,存入数据库操作,存入消息队列
$redis = new \Redis();
$redis -> connect('127.0.0.1',6379);
$phone = Session::get('phone');
$user = Session::get('username');
if(!$phone && !$user){
$this -> error('未登录');
}
if (extension_loaded('redis')){ //如果开启redis拓展,则:
// $count = Db::table('store_seckill') -> find(); //查询优惠券的数量
if(!$redis->get('count')){
$redis->set('count',100); //优惠券为100张,保存在redis
$redis -> expire('count',3600);
}
$count = $redis->get('count');
if($count<1){ //如果库存小于0
$this -> error('优惠券抢完啦!');
return;
}
if($count>0){
if($redis->lpush("miao",$phone)){ //插入数据入栈 //抢到优惠券了
$res = '抢购成功!';
--$count;
$redis->hset('status',$phone,1); //限制用户只能抢购一张券
$redis -> expire('status',3600);
}
}
if($redis->lLen('miao') >= 10){ //将redis队列的数据存进mysql里
$listItems = $redis->lRange('miao',0,10); //队列里满10条数据就可以存进数据库里了
foreach ($listItems as $key=>$val){ //将数据循环存进mysql
$value = Db::table('store_user')->where('phone',$val) -> value('disc');
$dat = $value+1;
$vv = Db::table('store_user')->where('phone',$val)->update(['disc'=>$dat]);
$redis->rpop('miao'); //每存入数据库一条,就删掉redis的一条数据
}
}
$this -> success($res);
}else{
$res = Db::table('store_user') -> where('phone',$phone) -> where('username',$user) -> find();
$count = Db::table('store_seckill') -> find(); //查询优惠券的数量
if($count['counts']<1){ //如果库存小于0
$this -> error('优惠券抢完啦!');
}
if($count['counts']>0){
$s = $res['disc']+1;
$h = $count['counts']-1;
Db::startTrans();
try{
$res2 = Db::table('store_user') -> where('id',$res['id']) -> update(['disc'=>$s]);
$res3 = Db::table('store_seckill') -> where('id',$count['id']) -> update(['counts'=>$h]);
// 提交事务
Db::commit();
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
$this -> error('抢购失败');
exit();
}
}else{
$this -> error('优惠券抢完啦~');
}
if($res){
$this -> success('抢购成功!');
}else{
$this -> error('抢购失败~');
}
}
}