在项目中使用消息队列一般是有如下几个原因:
把瞬间服务器的请求处理换成异步处理,缓解服务器的压力
实现数据顺序排列获取
redis实现消息队列步骤如下:
1).redis函数rpush,lpop
2).建议定时任务入队列
3)创建定时任务出队列
文件:demo.php插入数据到redis队列
<?php $redis = new Redis(); $redis->connect('127.0.0.1',6379); $password = '123456'; $redis->auth($password); $arr = array('h','e','l','l','o','w','o','r','l','d'); foreach($arr as $k=>$v){ $redis->rpush("mylist",$v); } ?>
文件:index.php定时扫描出队列
<?php $redis = new Redis(); $redis->connect('127.0.0.1',6379); $password = '123456'; $redis->auth($password); //list类型出队操作 $value = $redis->lpop('mylist'); if($value){ echo "出队的值".$value; }else{ echo "出队完成"; } ?>
建立定时任务
*/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 )
定时任务执行队列写入结果如下
127.0.0.1:> lrange mylist - ) "h" ) "e" ) "l" ) "l" ) "o" ) "w" ) "o" ) "r" ) "l" ) "d"
定时任务执行出队列后:
127.0.0.1:> lrange mylist - ) "e" ) "l" ) "l" ) "o" ) "w" ) "o" ) "r" ) "l" ) "d"