這里會用到ftok()函數,點擊官方文檔地址:
ftok
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
ftok — Convert a pathname and a project identifier to a System V IPC key
說明
ftok ( string
$pathname
, string $proj
) : int
The function converts the pathname
of an existing accessible file and a project identifier into an integer for use with for example shmop_open() and other System V IPC keys.
以上解釋:大意$pathname是文件名(需要確保文件可讀), $proj是自己定義的標識,得到的就是一個可訪問的路徑名和一個整數標識符轉換成一個key_t值。
新建msg_send.php
<?php $key = ftok(__DIR__, 'p'); echo($key . PHP_EOL); #隊列資源句柄 $queue = msg_get_queue($key); //var_dump($queue); #隊列狀態信息 $info = msg_stat_queue($queue); //var_export($info); $i = 0; while($i++ < 10) { msg_send($queue, 1, '吃飯了嗎? ' . $i , false, false); }
同級目錄新建msg_receive.php
<?php
$index = $argv[1];
$key = ftok(__DIR__, 'p'); $queue = msg_get_queue($key); echo("queue_key:" . $key . PHP_EOL);
//這里是阻塞模式,不會因為while(true)而陷入死循環,內存爆滿的情況 while(true) { msg_receive($queue, 0, $msg_type, 1024, $message, false, 0); echo('index: ' . $index . ', message: ' .$message);
sleep(2);//增加耗時方便展示演示效果 }
開始執行
[root@guangzhou msg]# php msg_send.php 1879117732 #為了增加演示效果,開了三個窗口同時運行msg_receive.php,分別傳參one, two, three [root@guangzhou msg]# php msg_receive.php one queue_key:1879117732
index: one, message: 吃飯了嗎? 1
index: one, message: 吃飯了嗎? 2
index: one, message: 吃飯了嗎? 5
index: one, message: 吃飯了嗎? 8 [root@guangzhou msg]# php msg_receive.php two queue_key:1879117732
index: two, message: 吃飯了嗎? 3
index: two, message: 吃飯了嗎? 6
index: two, message: 吃飯了嗎? 9 [root@guangzhou msg]# php msg_receive.php three queue_key:1879117732
index: three, message: 吃飯了嗎? 4
index: three, message: 吃飯了嗎? 7
index: three, message: 吃飯了嗎? 10 #通過腳本輸出可以看到類似redis隊列讀取的效果
#最后如果不需要可以銷毀隊列msg_remove_queue($queue)
注意:如果腳本運行期間ftok()函數計算數值發生改變,更改前后讀取的隊列名可能不一致,比如文件執行前被創建,執行中被刪除或重新創建或文件內容本身變動,兩次得到的ftok可能會不一樣。
系統關機后存在隊列中的數據會被銷毀,重啟無法恢復。