队列
1.将用户信息存到redis
<?php
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$redisName = "miaosha";
for($i = 0; $i < 100; $i++){
//接收用户的uid
$uid = rand(1,999999);
//规定抢购的数量
$num = 10;
//如果少于10则加入这个队列
if($redis->lLen($redisName) < 10){
$redis->rPush($redisName,$uid.'%'.microtime());
echo $uid."秒杀成功"."<br>";
}else{
echo "秒杀已经结束"."<br>";
}
}
$redis->close();
?>
2.停止秒杀活动 操作队列将信息刷到mysql中
<?php
$dbms='mysql'; //数据库类型
$host='localhost'; //数据库主机名
$dbName='test'; //使用的数据库
$user='root'; //数据库连接用户名
$pass='123456'; //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";
$dbh = new PDO($dsn, $user, $pass);
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$redisName = "miaosha";
//死循环
while(1){
//队列左侧取值
$user = $redis->lPop($redisName);
//判断值是否存在
if(!$user || $user == 'nil'){
sleep(2);
continue;
}
//切割时间
$userArr = explode('%',$user);
$uid = $userArr[0];
$time = date("Y-m-d H:i:s",time());
$res = $dbh->query("INSERT INTO redis (id,uid,time) VALUES (NULL,$uid,'$time')");
//如果失败 丢回队列
if(!$res){
$redis->rPush($redisName,$uid);
}
sleep(2);
}
//释放redis
$redis->close();
?>
redis事务
- 监视
<?php
$redis = new redis();
$redis->conect("127.0.0.1",6379);
//redis监视 redis事务在执行之前,检测这个key ,检测版本是否一致,不一致不会执行
$redis->watch("count");
//库存
$store = 3;
//记录销售量
$count = $redis->get("count");
if($count >= $store){
exit("活动结束");
}
$redis->multi();
$redis->incr("count");//销量+1
sleep(1);
$res = $redis->exec();//检测版本标识
//抢购成功
if($res){
include "db.php";
sqli();
}
?>
- 数据库(db.php)
<?php
$dbhost = '127.0.0.1'; // mysql服务器主机地址
$dbuser = 'root'; // mysql用户名
$dbpass = 'root'; // mysql用户名密码
function sqli(){
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){
die('Could not connect: ' . mysqli_error());
}
// 设置编码,防止中文乱码
mysqli_query($conn , "set names utf8");
$sql = 'UPDATE shop SET store=store-1 WHERE runoob_id=1';
mysqli_select_db( $conn, 'test' );
$retval = mysqli_query( $conn, $sql );
mysqli_close($conn);
}
?>