首先測試一個消息隊列的例子:
use Swoole\Coroutine as co;
$channel = new co\Channel(100);
co::create(function() use($channel){
for($i = 0; $i < 20; $i++) {
co::sleep(1.0);
$channel->push(['key'=>$i,'value'=>rand(111111,999999)]); //數組
echo "$i\n";
}
});
var_dump($channel->length());
swoole_event::wait()
演示結果:
可以看到,程序先返回的是消息隊列的數量,我看官方這個例子下面有人提問說爲什麼隊列數量一直是0,看到這個顯示結果應該明白了,程序是執行到協程代碼的地方直接返回結果,然後在執行協程裏面的代碼,就如上圖所示。那怎麼能查詢到當前內存中消息隊列的數量呢,我想有兩種方法,一種在添加消息隊列過後直接查詢數量,第二種在服務器中使用消息隊列,服務器沒有關閉之前,只要消息隊列裏面的消息沒有被消費,就可以查詢到消息隊列的數量和狀態。估計要使用協程服務器纔可以。
第一種代碼很簡單,在echo "$i\n"; 的後面加上 var_dump($channel->length()); 插入一條,顯示一下消息隊列的數量。下面是第二種方法:
use Swoole\Coroutine as co;
$channel = new co\Channel(100);
go(function () use($channel){
$server = new Co\Http\Server("127.0.0.1", 8888, false);
$server->handle('/', function ($request, $response) use($channel,$server){
if(strpos($request->server['request_uri'],'.ico') !== false){
$response->end("");
}else{
echo "開始創建消息隊列,推入10個消息".PHP_EOL;
co::create(function() use($channel){
for($i = 0; $i < 10; $i++) {
$channel->push(['key'=>$i,'value'=>rand(111111,999999)]); //數組
}
});
$response->header("Content-Type","text/html; charset=UTF-8");
$response->end("<h1>創建了".$channel->length()."消息</h1>");
}
});
$server->handle('/test', function ($request, $response) use($channel,$server){
if(strpos($request->server['request_uri'],'.ico') !== false){
$response->end("");
}else{
echo "查看消息隊列".PHP_EOL;;
$response->header("Content-Type","text/html; charset=UTF-8");
$response->end("<h1>查看消息的個數:".$channel->length()."</h1>");
}
});
$server->handle('/stop', function ($request, $response) use ($channel,$server) {
if(strpos($request->server['request_uri'],'.ico') !== false){
$response->end("");
}else{
$response->header("Content-Type","text/html; charset=UTF-8");
$response->end("<h1>消費一個消息:".json_encode($channel->pop())."</h1>");
//$server->shutdown();
}
});
$server->start();
});
演示結果如下:
每次添加10個消息,查看隊列數量。消費一個消息,當添加到100消息的時候,後面添加的消息阻塞在隊列之外,等待消費者消費消息在100以下,後面的消息才能入隊。不然會一直阻塞等待在隊列之外等待入隊。
以上就是消息隊列的簡單例子,感覺用起來有點單一,難道整個服務器啓動之後就只能創建以個數爲名字的消息隊列嗎?我創建兩個消息隊列相互影響嗎? 還需要繼續探究一下。