1. nginx的基本配置
server {
listen 80;
server_name codeigniter.localhost;
root /var/www/html/codeigniter;
index index.php index.html;
access_log /tmp/nginx_access.log;
# set expiration of assets to MAX for caching
location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
expires max;
log_not_found off;
}
location / {
# Check if a file or directory index file exists, else route it to index.php.
try_files $uri $uri/ /index.php;
}
location ~* \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_read_timeout 600;
}
}
2. 增加最大连接数,支持高并发
设置nginx的最大连接数,以及多核CPU设置。
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
worker_rlimit_nofile 102400;
events {
worker_connections 102400;
# multi_accept on;
}
解决错误:
*4645 socket() failed (24: Too many open files)
增大nginx可以接受的并发数,以应对高并发。
访问量高时,由于系统对于进程的最大文件打开数的限制(ulimit -n 默认1024),而nginx属于单进程多线程并发的服务,所以在访问量高时,连接数超过1024后,会被系统限制连接。所以还需要设置ulimit的支持的最大文件描述符。
在文件:/etc/security/limits.conf 中增加下面的两行配置
* soft nofile 655360
* hard nofile 655360
然后重启生效, ulimit -a 查看可以支持的文件数。
3. PHP-FPM 的设置
为PHP-FPM设置最大连接数。
这一块写的比较虚,很多参数我也还没有弄得很明白,内存够用的时候在一定的程度上可以增加并发数。
pm.mac_children的值需要根据情况来定。在我的Ubuntu 16.04下面,修改以下两个文件:
/etc/php/7.0/fpm/php-fpm.conf
process.max = 300
rlimit_files = 8192
/etc/php/7.0/fpm/pool.d/www.conf
pm = static
pm.max_children = 200
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
4. 性能测试
我的虚拟机Ubuntu 16.04 LTS的硬件性能如下:
四核 Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz
4GB 内存
测试locahost的hello.html 的结果如下:
A. ab -c 100 -n 1000 http://localhost:8000/hello.html
hello.html的代码
hello world
测试结果如下:
Requests per second: 10389.29 [#/sec] (mean)
Time per request: 9.625 [ms] (mean)
Time per request: 0.096 [ms] (mean, across all concurrent requests)
Transfer rate: 2546.59 [Kbytes/sec] received
B. ab -c 100 -n 1000 http://localhost:8000/hello.php
hello.php的代码如下:
<?php
echo "hello world";
测试结果如下:
Requests per second: 5154.29 [#/sec] (mean)
Time per request: 19.401 [ms] (mean)
Time per request: 0.194 [ms] (mean, across all concurrent requests)
Transfer rate: 790.26 [Kbytes/sec] received
C. ab -c 100 -n 1000 http://codeigniter.localhost:8000/welcome/hello
CI 3.0 的稳定版的,在Welcome这个controller下面实现hello方法:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
echo "hello";
}
public function hello()
{
echo "hello world";
}
}
测试结果如下:
Requests per second: 1652.19 [#/sec] (mean)
Time per request: 60.526 [ms] (mean)
Time per request: 0.605 [ms] (mean, across all concurrent requests)
Transfer rate: 253.31 [Kbytes/sec] received