<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> </head> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <body> <p><span id="uid1">0</span><input type="button" value="用户1" onclick="vote(1);" /></p> <p><span id="uid2">0</span><input type="button" value="用户2" onclick="vote(2);" /></p> <p><span id="uid3">0</span><input type="button" value="用户3" onclick="vote(3);" /></p> </body> <script> function vote(i){ $.get('vote.php?uid='+i,function(rs){ var span = '#uid'+i; $(span).html(rs); }); } </script> </html> |
<?php $redis = new Redis(); $redis->connect('localhost',6379); //计算每个用户的总票数 $uid = intval($_GET['uid']); //$uid = mt_rand(1,3);//随机指定投票人员,方便进行压力测试 echo $redis->incr($uid); $voteid = $redis->incr('global_voteid'); $redis->set('vote:'.$voteid.':uid',$uid); $ip = $_SERVER['REMOTE_ADDR']; $redis->set('vote:'.$voteid.':ip',$ip); $redis->set('vote:'.$voteid.':time',time()); |
<?php //连接数据库 $pdo = new PDO('mysql:host=localhost;dbname=test','root','1234'); $pdo->query('set names utf8'); //连接redis $redis = new Redis(); $redis->connect('localhost',6379); //永真循环 while(true){ $vid = $redis->get('global_voteid');//自增长的主键 $last = $redis->get('last');//最近一次插入mysql的投票主键 //如果没有插入数据库,刚开始的肯定为true if(!$last){ $last = 0;//设置为0 } //如果所有的数据都被插入到MySQL中 if($vid == $last){ echo "wait\n";//输出等待 }else{ //进行插入到数据库操作 $sql = 'insert into vote(vid,uid,ip,time) values'; for($i = $vid;$i>$last;$i--){ $k1 = 'vote:'.$i.':uid'; $k2 = 'vote:'.$i.':ip'; $k3 = 'vote:'.$i.':time'; $row = $redis->mget([$k1,$k2,$k3]); $sql.="($i,$row[0],'$row[1]',$row[2]),"; $redis->delete($k1,$k2,$k3); } $sql = substr($sql,0,-1); $pdo->exec($sql); $redis->set('last',$vid);//设置插入的主键位置 echo 'OK'; } sleep(5);//每隔5秒执行循环 } |