把瞬間伺服器的請求處理換成非同步處理,緩解伺服器的壓力,實現資料順序排列擷取。本文主要和大家分享php和redis如何?訊息佇列,希望能協助到大家。
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:6379> lrange mylist 0 -1 1) "h" 2) "e" 3) "l" 4) "l" 5) "o" 6) "w" 7) "o" 8) "r" 9) "l" 10) "d"
定時任務執行出隊列後:
127.0.0.1:6379> lrange mylist 0 -11) "e"2) "l"3) "l"4) "o"5) "w"6) "o"7) "r"8) "l"9) "d"