̽ÌÖSwooleÖÐг̵ÄÔËÐлúÖÆ
swooleÊÇÒ»¸ö»ùÓÚphpµÄг̿ò¼Ü£¬ËüµÄÒì²½ioÐÔÄܺÜÊǾ«²Ê¡£swooleµÄ½¹µãÊÇг̣¬Ð³ÌÊÇÒ»ÖÖ±ÈÏ̸߳üÇáÁ¿¼¶µÄ²¢·¢»úÖÆ£¬¿ÉÒÔÔÚͳһÏß³ÌÖÐÇл»Ê¹ÃüÀ´ÊµÏÖ²¢·¢Ö´ÐС£±¾ÎĽ«»á̽ÌÖswooleÖÐг̵ÄÔËÐлúÖÆ¡£
Ò»¡¢Ð³ÌµÄ¿´·¨
г̣¬ÓÖ³Æ΢Ị̈߳¬ÊÇÒ»ÖÖ±ÈÏ̸߳üϸÁ£¶ÈµÄ²¢·¢»úÖÆ¡£Ð³ÌÓëÏ̵߳ÄÇø±ðÔÚÓÚ£¬Ð³Ìͨ¹ýʱ¼äƬÂÖתÀ´ÊµÏÖʹÃüÇл»£¬¶øÏß³ÌÓɲÙ×÷ϵͳµ÷ÀíÆ÷ÈÏÕæÇл»¡£Òò´Ë£¬Ð³ÌÔÚÐÔÄÜÉϱÈÏß³ÌÔ½·¢¾«²Ê¡£
ÔÚSwooleÖУ¬Ð³ÌÊÇÒ»ÖÖÇáÁ¿¼¶µÄPHPÏ̡߳£Ð³Ì¿ÉÒÔÔÚͳһÏß³ÌÖÐÇл»Ö´Ðвî±ðµÄʹÃü£¬ÊµÏÖ²¢·¢Ö´ÐС£Ïà±ÈÓڹŰåµÄÏ̳߳Øģʽ£¬Ð³Ì¿ÉÒÔ×èÖ¹Ïß³ÌÉÏÏÂÎÄÇл»µÄ¿ªÏú£¬Í¬Ê±Ð³Ì¾ßÓиüµÍµÄÄÚ´æÕ¼Óú͸ü¸ßµÄÖ´ÐÐЧÂÊ¡£
¶þ¡¢SwooleµÄгÌʵÏÖ
Swooleͨ¹ýг̵÷ÀíÆ÷À´ÊµÏÖг̵ĵ÷ÀíºÍÇл»£¬Ð³Ìµ÷ÀíÆ÷ÊÇSwooleÌṩµÄÒ»ÖÖг̵÷ÀíÒýÇ棬Ëü¿ÉÒÔ»ùÓÚʱ¼äƬÂÖתµÄ·½·¨ÀÍÆÈ´»Ð³ÌÖ´ÐÐʹÃü¡£
г̵÷ÀíÆ÷µÄʵÏÖÔÀíÈçÏ£º
1.Ê×ÏÈ£¬µ÷ÀíÆ÷»áΪÿ¸öг̷ÖÅÉÒ»¸ö״̬£¬Àý×¼ÆÚ´ý¡¢Ö´ÐС¢ÐÝÃߵȡ£
2.µ÷ÀíÆ÷»áͨ¹ýÒ»¸öʹÃüÐÐÁÐÀ´ÖÎÀíËùÓÐг̵Ä״̬¡£µ±Ä¿½ñгÌÖ´ÐÐÍê³Éºó£¬µ÷ÀíÆ÷»áÓÅÏÈÑ¡Ôñ״̬ΪÆÚ´ýµÄгÌÀ´Ö´ÐС£
3.г̻áÔÚÖ´ÐÐÀú³ÌÖÐ×Ô¶¯ÅжÏÄ¿½ñʹÃüÊÇ·ñÍê³É¡£ÈôÊÇÄ¿½ñʹÃüδÍê³É£¬Ð³Ì»á½«Æä¹ÒÆð£¬È»ºóÇл»µ½ÆäËûгÌÖ´ÐУ¬Ö±µ½ÏÂÒ»´Îµ÷ÀíʱÔÙ¼ÌÐøÖ´ÐйÒÆðʹÃü¡£
4.ÔÚгÌÖ´ÐÐʱ´ú£¬ÈôÊÇ·ºÆðIOÛÕ±Õ²Ù×÷£¨ÀýÈçÍøÂçIO¡¢ÎļþIO¡¢Êý¾Ý¿âÅÌÎʵȣ©£¬Ð³Ì»á×Ô¶¯¹ÒÆ𣬲¢½«Ä¿½ñʹÃü״̬ÉèÖÃΪÐÝÃß¡£µ±IOÛÕ±ÕÍê³Éºó£¬Ð³Ì»á×Ô¶¯½ÐÐÑ£¬²¢½«Ê¹Ãü״̬ÉèÖÃΪִÐС£
5.ÔÚгÌÖ´ÐÐÍê³Éºó£¬µ÷ÀíÆ÷»á½ÓÄÉ×ÊÔ´£¬²¢½«Ð³Ì״̬ÉèÖÃΪ¿¢Ê¡£
Èý¡¢SwooleµÄгÌÓÅÊÆ
SwooleµÄг̾ßÓÐÒÔÏÂÓŵ㣺
1.¸ßЧ£ºÐ³ÌÄܹ»ÔÚͳһÏß³ÌÖÐÇл»Ê¹ÃüÖ´ÐУ¬×èÖ¹ÁËÏß³ÌÉÏÏÂÎÄÇл»µÄ¿ªÏú£¬Í¬Ê±¼ÓËÙÁË´úÂëÖ´ÐÐËÙÂÊ¡£
2.ÇáÁ¿¼¶£ºÐ³ÌÕ¼ÓõÄÄÚ´æ×ÊÔ´ºÜÊÇÉÙ£¬¿ÉÒÔͬʱ֧³Ö´ó×Ú²¢·¢ÅþÁ¬¡£
3.Ò×ÓÚµ÷ÊÔ£ºÐ³ÌÄܹ»Ìṩ¸üϸÁ£¶ÈµÄµ÷ÊÔÐÅÏ¢£¬Àû±ã¿ª·¢Õß¾ÙÐе÷ÊÔ¡£
4.Ò×ÓÚά»¤£ºÐ³ÌµÄ´úÂë±È¹Å°åµÄ¶àÏ̴߳úÂë¸ü¼òÆÓ£¬Ò×ÓÚά»¤¡£
ËÄ¡¢Swooleг̵ÄʹÓð취
1.ÒýÈëSwooleµÄг̿â
SwooleµÄг̿â¿ÉÒÔͨ¹ýComposerÖ±½ÓÒýÈ룬ÏÂÁîÈçÏ£º
composer require swoole/Coroutine
2.±àдг̴úÂë
ÔÚSwooleµÄгÌÖУ¬¿ÉÒÔʹÓÃÒªº¦×ÖyieldÀ´ÊµÏÖгÌÇл»¡£ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄʾÀý£º
function test()
{
echo "coroutine starts", PHP_EOL; $result = yield select(null, null, null, 0.5); echo "coroutine ends, selected: ", $result, PHP_EOL;
µÇ¼ºó¸´ÖÆ
}
// Æô¶¯Ð³Ì
go(function () {
test();
µÇ¼ºó¸´ÖÆ
});
3.ÔËÐÐSwooleгÌЧÀÍ
ʹÓÃSwooleÌṩµÄServerÀàÀ´½¨ÉèÒ»¸öгÌЧÀÍ£º
Coun(function () {
$server = new Server('0.0.0.0', 9501, SWOOLE_BASE); $server->on('Connect', function ($server, $fd) { echo "Client $fd connected
µÇ¼ºó¸´ÖÆ
“;
}); $server->on('Receive', function ($server, $fd, $from_id, $data) { echo "Client $fd: $data
µÇ¼ºó¸´ÖÆ
“;
$server->send($fd, "Server received
µÇ¼ºó¸´ÖÆ
“);
}); $server->on('Close', function ($server, $fd) { echo "Client $fd closed
µÇ¼ºó¸´ÖÆ
“;
}); $server->start();
µÇ¼ºó¸´ÖÆ
});
ÔÚSwooleµÄгÌЧÀÍÖУ¬¿ÉÒÔʹÓÃgoÒªº¦×ÖÀ´½¨Éèг̣¬ÀýÈ磺
go(function () {
// гÌÖ´ÐеÄʹÃü
µÇ¼ºó¸´ÖÆ
});
Îå¡¢×ܽá
SwooleµÄгÌʵÏÖÊÇÒ»ÖÖºÜÊǸßЧºÍÇáÁ¿¼¶µÄ²¢·¢»úÖÆ£¬Äܹ»ÓÐÓýâ¾öPHPÔڸ߲¢·¢³¡¾°ÏµÄÐÔÄÜÎÊÌ⡣ͨ¹ý±¾ÎÄÎÒÃÇÏàʶÁËSwooleÖÐг̵ÄÔËÐлúÖƺÍʹÓÃÒªÁ죬ÐÅÍжÁÕ߶ÔSwooleµÄгÌÒ²ÓÐÁ˸üÉîÈëµÄÊìϤ¡£
ÒÔÉϾÍÊÇ̽ÌÖSwooleÖÐг̵ÄÔËÐлúÖƵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡