php+redis实现消息队列
个人理解在项目中使用消息队列一般是有如下几个原因:
-
把瞬间服务器的请求处理换成异步处理,缓解服务器的压力
-
实现数据顺序排列获取
redis实现消息队列步骤如下:
1).redis函数rpush,lpop
2).建议定时任务入队列
3)创建定时任务出队列
文件:demo.php插入数据到redis队列
1 <?php 2 3 $redis = new Redis(); 4 5 $redis->connect('127.0.0.1',6379); 6 7 $password = '123456'; 8 9 $redis->auth($password); 10 11 $arr = array('h','e','l','l','o','w','o','r','l','d'); 12 13 foreach($arr as $k=>$v){ 14 15 $redis->rpush("mylist",$v); 16 17 }
文件:index.php定时扫描出队列
1 <?php 2 3 $redis = new Redis(); 4 5 $redis->connect('127.0.0.1',6379); 6 7 $password = '123456'; 8 9 $redis->auth($password); 10 11 //list类型出队操作 12 13 $value = $redis->lpop('mylist'); 14 15 if($value){ 16 17 echo "出队的值".$value; 18 19 }else{ 20 21 echo "出队完成"; 22 23 } 24 25 ?>
建立定时任务
*/1 * * * * root php /wwwroot/workplace/redis/index.php
*/3 * * * * root php /wwwroot/workplace/redis/demo.php
tail -f /var/log/cron 查看定时任务执行情况
Nov 7 00:30:01 dongzi CROND[6888]: (root) CMD (php /wwwroot/workplace/redis/demo.php)
Nov 7 00:30:01 dongzi CROND[6890]: (root) CMD (php /wwwroot/workplace/redis/index.php )
定时任务执行队列写入结果如下
1 127.0.0.1:6379> lrange mylist 0 -1 2 3 1) "h" 4 5 2) "e" 6 7 3) "l" 8 9 4) "l" 10 11 5) "o" 12 13 6) "w" 14 15 7) "o" 16 17 8) "r" 18 19 9) "l" 20 21 10) "d"
定时任务执行出队列后:
1 127.0.0.1:6379> lrange mylist 0 -1 2 3 1) "e" 4 5 2) "l" 6 7 3) "l" 8 9 4) "o" 10 11 5) "w" 12 13 6) "o" 14 15 7) "r" 16 17 8) "l" 18 19 9) "d"
文章转自:https://www.cnblogs.com/lisqiong/p/6039460.html