標籤:nts lin foreach img ons password ash comm cin
?
個人理解在項目中使用訊息佇列一般是有如下幾個原因:
把瞬間伺服器的請求處理換成非同步處理,緩解伺服器的壓力
實現資料順序排列擷取
?redis實現訊息佇列步驟如下:
1).redis函數rpush,lpop
2).建議定時任務入隊列
3)建立定時任務出隊列
檔案:demo.php插入資料到redis隊列
1234567891011121314151617 |
<?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定時掃描出隊列
12345678910111213141516171819202122232425 |
<?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 )
定時任務執行隊列寫入結果如下
123456789101112131415161718192021 |
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"
php+redis實現訊息佇列