通過TCMalloc來優化nginx
TCMalloc(Thread-Caching Malloc)是google開發的開源工具gperftools中的一個成員,tcmalloc比glibc中的malloc記憶體分配效率要快,tcmalloc特別對多執行緒做了優化,很大程度提高了伺服器在高併發下的效能,從而降低了系統的負載。
tcmalloc屬於gperftools,安裝前提必須安裝libunwind(32位系統不需要安裝),libunwind庫為基於64位cpu和作業系統的程式提供了基本函式呼叫鏈和函式呼叫暫存器功能。
一、下載相關軟體包
官方下載地址:
https://github.com/gperftools/gperftools/releases/download/gperftools-2.7/gperftools-2.7.tar.gz
https://download-mirror.savannah.gnu.org/releases/libunwind/libunwind-1.2.tar.gz
本地下載地址:
http://down.whsir.com/downloads/gperftools-2.7.tar.gz
http://down.whsir.com/downloads/libunwind-1.2.tar.gz
1234 | cd/usr/local/src/wget http://nginx.org/download/nginx-1.14.0.tar.gzwget http://down.whsir.com/downloads/gperftools-2.7.tar.gzwget http://down.whsir.com/downloads/libunwind-1.2.tar.gz |
二、安裝所需依賴
1 | yum install gcc gcc-c++pcre pcre-devel openssl openssl-devel zlib zlib-devel |
三、建立nginx啟動使用者
1 | useradd-s/bin/false-Mwww |
四、解壓編譯安裝libunwind和gperftools
12345678910111213 | tar zxf libunwind-1.2.tar.gzcd libunwind-1.2CFLAGS=-fPIC./configuremake CFLAGS=-fPICmake CFLAGS=-fPIC installcd..tar zxf gperftools-2.7.tar.gzcd gperftools-2.7./configuremakemake installecho"/usr/local/lib">>/etc/ld.so.confldconfig |
五、編譯nginx
編譯時要新增--with-google_perftools_module引數,我這裡使用的全新nginx編譯,如果已有編譯好的nginx,只需要執行前面第二步後單獨新增一個--with-google_perftools_module引數重新編譯即可
123456 | cd..tar zxf nginx-1.14.0.tar.gzcd nginx-1.14.0./configure--user=www--group=www--prefix=/usr/local/nginx--with-http_stub_status_module--with-http_ssl_module--with-http_v2_module--with-http_gzip_static_module--with-http_sub_module--with-google_perftools_modulemakemake install |
設定個軟連線
1 | ln-sv/usr/local/nginx/sbin/nginx/usr/local/sbin/ |
設定systemctl
1 | vi/usr/lib/systemd/system/nginx.service |
123456789101112 | [Unit]Description=nginxAfter=network.target[Service]Type=forkingPIDFile=/usr/local/nginx/logs/nginx.pidExecStart=/usr/local/nginx/sbin/nginxExecReload=/usr/local/nginx/sbin/nginx-sreloadExecStop=/usr/local/nginx/sbin/nginx-sstopPrivateTmp=true[Install]WantedBy=multi-user.target |
六、為gperftools建立一個執行緒目錄
12 | mkdir/tmp/tcmallocchmod777/tmp/tcmalloc/ |
七、配置nginx.conf
在#pid logs/nginx.pid;下面增加一行
1 | google_perftools_profiles/tmp/tcmalloc; |
八、最後啟動nginx並驗證
123 | nginx-tsystemctl start nginxsystemctl enable nginx |
12 | lsof-n|grep tcmallocnginx16534www10wREG0,37080796/tmp/tcmalloc.16534 |
這裡看到有多少條記錄是根據nginx的worker_processes執行緒數來的
贊 0