PHP的异步并行swoole扩展在1.7.7中内置了一个Http服务器,利用swoole_http_server能够轻松实现一个PHP的异步Web服务器,性能比php-fpm/Apache等同步阻塞的服务器高出数倍。php
swoole官方还提供了redis-async,一个异步IO+链接池的Redis客户端。这2个功能结合起来就能够打造一个并发请求数万的Web应用。nginx
能够使用pecl安装或者从github下载swoole最新的stable版本。git
pecl install swoole
修改php.ini加入extension=swoole.sogithub
git clone https://github.com/swoole/redis-async.git
$http = new swoole_http_server("127.0.0.1", 9501); $http->set(['worker_num' => 8]); require __DIR__.'/src/Swoole/Async/RedisClient.php'; $redis = new Swoole\Async\RedisClient('127.0.0.1'); $http->on('request', function ($request, $response) use ($redis) { $redis->get('key1', function($result) use($response) { $response->end("<h1>Hello Swoole. value=".$result."</h1>"); }); }); $http->start();
运行server.php程序,这里一共启动了8个进程。注意因为是异步非阻塞的服务器程序,因此不须要像Apache/PHP-fpm那样开启数百的进程。这里彻底是没有等待的,所有是事件驱动。当请求到来发起redis请求,redis-server响应后会触发对应的事件,再渲染页面,将HTML页面经过$response->end接口发送给浏览器。redis
php server.php
Http服务器启动监听了9501端口,浏览器中能够打开 http://127.0.0.1:9501 访问页面。本程序的逻辑很简单,只是从redis中取一个数据,并渲染页面。shell
ab -c 200 -n 100000 -k http://127.0.0.1:9501/
机器环境是:Inter CoreI5 4核CPU+8G内存,Ubuntu 14.04浏览器
压测结果:服务器
Server Software: swoole-http-server Server Hostname: 127.0.0.1 Server Port: 9501 Document Path: / Document Length: 40 bytes Concurrency Level: 200 Time taken for tests: 2.853 seconds Complete requests: 100000 Failed requests: 0 Keep-Alive requests: 100000 Total transferred: 16800000 bytes HTML transferred: 4000000 bytes Requests per second: 35049.02 [#/sec] (mean) Time per request: 5.706 [ms] (mean) Time per request: 0.029 [ms] (mean, across all concurrent requests) Transfer rate: 5750.23 [Kbytes/sec] received
能够达到3.5万QPS,性能惊人,仅仅使用一台普通的PC机器,硬件性能通常。若是是在服务器硬件环境中,性能能够更好。swoole
PHP-fpm已开启OpCache,采用phpredis扩展,已启用pconnect长链接,测试启动80进程。测试代码以下:
并发
$redis = new redis; $redis->pconnect('127.0.0.1'); $result = $redis->get('key1'); echo "<h1>Hello Swoole. value=".$result."</h1>";
测试结果:
Server Software: nginx/1.4.6 Server Hostname: 127.0.0.1 Server Port: 80 Document Path: /redis.php Document Length: 40 bytes Concurrency Level: 200 Time taken for tests: 15.605 seconds Complete requests: 100000 Failed requests: 0 Keep-Alive requests: 0 Total transferred: 21000000 bytes HTML transferred: 4000000 bytes Requests per second: 6408.33 [#/sec] (mean) Time per request: 31.209 [ms] (mean) Time per request: 0.156 [ms] (mean, across all concurrent requests) Transfer rate: 1314.21 [Kbytes/sec] received