SwooleÓëMemcachedµÄÕûºÏ£º¼ÓËÙWebÓ¦ÓóÌÐò
Ëæ×ÅwebÓ¦ÓóÌÐòµÄÖØ´óÐԺ͸ºÔØÔ½À´Ô½´ó£¬ÔõÑùÌáÉýwebÓ¦ÓóÌÐòµÄÐÔÄܳÉΪÁËÿһ¸öweb¿ª·¢Ö°Ô±ÃæÁÙµÄÖØ´óÌôÕ½¡£¹Å°åµÄweb¿ª·¢ÖУ¬memcachedÊÇÊ¢ÐеĻº´æÊÖÒÕÖ®Ò»£¬¿ÉÒÔ¼«´óµØÌá¸ßwebÓ¦ÓóÌÐòµÄÏìӦʱ¼ä¡£¶øswooleÊÇ×î½üÐËÆðµÄÒì²½ÍøÂç±à³Ì¿ò¼Ü£¬¿ÉÒÔ½«phpµÄwebÓ¦ÓóÌÐòת»»ÎªÒì²½ÊÂÎñÇý¶¯µÄ·½·¨£¬´Ó¶ø½øÒ»²½Ìá¸ßwebÓ¦ÓóÌÐòµÄÐÔÄÜ¡£ÕâƪÎÄÕ½«ÏÈÈÝÔõÑù½«swooleºÍmemcachedÕûºÏ£¬Ò»Æð¼ÓËÙwebÓ¦ÓóÌÐò¡£
ʲôÊÇSwooleºÍMemcached
ÔÚÏÈÈÝÔõÑùÕûºÏSwooleºÍMemcached֮ǰ£¬ÎÒÃÇÐèÒªÏàʶһÏÂËüÃǸ÷×ÔÊÇʲô¡£
SwooleÊÇÒ»¸ö»ùÓÚÊÂÎñÇý¶¯µÄÒì²½ÍøÂçͨѶ¿ò¼Ü£¬Éè¼Æ³õÖ¾ÊÇΪÏàʶ¾öPHPÔڸ߲¢·¢¡¢¸ß¸ºÔصÄÇéÐÎÏÂÐÔÄܵÍϵÄÎÊÌâ¡£Swoole½ÓÄÉÁ˶àÀú³Ì¡¢¶àÏ̵߳ķ½·¨À´³ä·ÖʹÓöàºËCPUµÄÐÔÄÜ£¬Í¬Ê±»¹Ö§³ÖÒì²½µÄMySQLºÍRedis¿Í»§¶Ë£¬¿ÉÒÔÈÃPHPÓ¦ÓóÌÐòÔÚÖ´ÐÐIO²Ù×÷ʱ²»»áÛÕ±ÕÖ÷Àú³Ì£¬´Ó¶øÌá¸ßWebÓ¦ÓóÌÐòµÄÐÔÄÜ¡£
MemcachedÊÇÒ»ÖÖ»ùÓÚÄÚ´æµÄ»º´æÊÖÒÕ£¬Ö÷ÒªÓÃÓÚ¼ÓËÙWebÓ¦ÓóÌÐòµÄÏìӦʱ¼ä¡£Memcached½«Êý¾Ý´æ´¢ÔÚÄÚ´æÖУ¬ÓëÊý¾Ý¿âÏà±È£¬¶ÁдËÙÂʸü¿ì¡£Memcached»¹Ö§³ÖÂþÑÜʽ¼Ü¹¹£¬¿ÉÒÔ½«Êý¾Ý´æ´¢ÔÚ¶ą̀ЧÀÍÆ÷ÉÏ£¬´Ó¶øÌá¸ß»º´æµÄÖÀÖÐÂʺͿɿ¿ÐÔ¡£
SwooleÓëMemcachedµÄÕûºÏ
SwooleÖ§³Ö¶àÏ̡߳¢¶àÀú³Ì£¬ÕâʹµÃËü¿ÉÒÔͬʱ´¦Àí¶à¸öHTTPÇëÇó¡£ÈôÊÇÎÒÃǽ«MemcachedÓÃ×÷»º´æЧÀÍÆ÷£¬ÄÇôÎÒÃǾͿÉÒÔʹÓÃSwooleµÄÒì²½IOÌØÕ÷ʵÏÖÔÚ·¢ËÍÇëÇóµ½MemcachedЧÀÍÆ÷Ö®ºó£¬Ö÷Àú³Ì¿ÉÒÔ¼ÌÐøÖ´ÐÐÆäËûʹÃü£¬²»±ØÆÚ´ýMemcachedЧÀÍÆ÷µÄÏìÓ¦¡£
ÎÒÃÇ¿ÉÒÔͨ¹ýÈçÏ·½·¨Ê¹ÓÃSwooleÓëMemcachedÕûºÏ£º
2.1 ×°ÖúÍÉèÖÃMemcachedЧÀÍÆ÷
Ê×ÏÈ£¬ÎÒÃÇÐèҪװÖúÍÉèÖÃMemcachedЧÀÍÆ÷¡£¿ÉÒÔͨ¹ýÒÔÏÂÏÂÁîÔÚUbuntuϵͳÉÏ×°ÖÃMemcached£º
sudo apt-get update sudo apt-get install memcached
µÇ¼ºó¸´ÖÆ
ÔÚ×°ÖÃÍê³Éºó£¬ÎÒÃÇÐèÒªÉèÖÃMemcachedЧÀÍÆ÷£¬¿ÉÒÔͨ¹ý±à¼/etc/memcached.confÎļþÀ´ÊµÏÖ¡£ÔÚ¸ÃÎļþÖУ¬¿ÉÒÔÉèÖüàÌý¶Ë¿Ú¡¢»º´æ¾ÞϸÒÔ¼°¿ÉÓõÄÄÚ´æÊýÄ¿µÈ²ÎÊý¡£ÉèÖÃÍê³Éºó£¬Í¨¹ýÒÔÏÂÏÂÁîÆô¶¯MemcachedЧÀÍÆ÷£º
sudo service memcached start
µÇ¼ºó¸´ÖÆ
2.2 ×°ÖÃSwooleÀ©Õ¹
ÔÚʹÓÃSwooleÓëMemcachedÕûºÏ֮ǰ£¬ÎÒÃÇÐèÒªÏÈ×°ÖÃSwooleÀ©Õ¹¡£¿ÉÒÔͨ¹ýÒÔÏÂÏÂÁîÔÚUbuntuϵͳÉÏ×°ÖÃSwooleÀ©Õ¹£º
sudo pecl install swoole
µÇ¼ºó¸´ÖÆ
×°ÖÃÍê³Éºó£¬ÐèÒªÔÚphp.iniÉèÖÃÎļþÖÐÆôÓÃSwooleÀ©Õ¹¡£
2.3 ±àдPHP´úÂë
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒª±àдPHP´úÂëÀ´Ê¹ÓÃSwooleÓëMemcachedÕûºÏ¡£ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃÇʹÓÃSwooleµÄHTTPЧÀÍÆ÷À´´¦ÀíËùÓеÄÇëÇ󣬲¢Ê¹ÓÃMemcached×÷Ϊ»º´æЧÀÍÆ÷¡£
<?php $http = new swoole_http_server("0.0.0.0", 9501); $http->on('request', function ($request, $response) { $memcached = new Memcached(); $memcached->addServer("127.0.0.1", 11211); $key = md5($request->server['request_uri']); $result = $memcached->get($key); if ($result !== false) { $response->end($result); } else { $result = file_get_contents("http://example.com"); $memcached->set($key, $result, 300); // »º´æ300Ãë $response->end($result); } }); $http->start();
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬µ±ÊÕµ½HTTPÇëÇóʱ£¬Ê×ÏÈʵÑé´ÓMemcachedЧÀÍÆ÷ÖвéÕÒ¸ÃÇëÇóµÄ»º´æЧ¹û¡£ÈôÊÇ»º´æÖÀÖУ¬ÔòÖ±½Ó·µ»ØЧ¹û¡£ÈôÊÇ»º´æδÖÀÖУ¬ÔòÖØÐÂÇëÇóexample.comÍøÕ¾²¢½«Ð§¹û´æ´¢µ½MemcachedЧÀÍÆ÷ÖС£
×ÛÉÏËùÊö£¬Ê¹ÓÃSwooleÓëMemcachedÕûºÏ¿ÉÒÔ¼«´óµØÌá¸ßWebÓ¦ÓóÌÐòµÄÐÔÄÜ¡£Í¨¹ýʹÓÃSwooleµÄÒì²½IOÌØÕ÷ºÍMemcachedµÄ¸ßËÙ»º´æÊÖÒÕ£¬¿ÉÒÔʹPHPÓ¦ÓóÌÐòÔڸ߲¢·¢¡¢¸ß¸ºÔصÄÇéÐÎÏÂÒÔ¸ü¿ìµÄËÙÂÊÏìÓ¦Óû§ÇëÇó¡£
ÒÔÉϾÍÊÇSwooleÓëMemcachedµÄÕûºÏ£º¼ÓËÙWebÓ¦ÓóÌÐòµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡