phar文件可以把用到的PHP文件全部打包在一個文件中,十分方便網站部署。但是單個的PHP文件可以使用opcache緩存(字節碼緩存),以提升PHP的運行速度。那麼PHAR文件包如何使用緩存呢。
這裏需要進行配置(php.ini)
phar.cache_list
手冊上的解釋爲:
Allows mapping phar archives to be pre-parsed at web server startup, providing a performance improvement that brings running files out of a phar archive very close to the speed of running those files from a traditional disk-based installation.
允許在web服務器啓動時預分析映射phar存檔,從而提供性能改進,使phar存檔中運行的文件的速度非常接近於從傳統的基於磁盤的安裝中運行這些文件的速度。
這個功能只有在phar 2.0.0開始支持。當然目前你安裝的PHP都是2以上的。phar 2.0.0 的發佈日期爲 2009-07-29。手冊上的配置說明。
# in php.ini (windows): phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar # in php.ini (unix): phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar
windows上多個文件使用分號,LINUX上使用冒號。
啓用了cache_list後,重啓php-fpm(或者可能是Apache)。
請確保opcache處於啓用狀態(php.ini):
opcache.enable=1
那麼效果如何呢?用我的NILCMS框架做測試。環境:
PHP 7.2.25
NGINX 1.14.2
CentOS 7.7.1908
測試命令:ab -n 500 -c 5 域名
1.opcache未啓用,cache_list未配置
Concurrency Level: 5
Time taken for tests: 7.665 seconds
Complete requests: 500
Failed requests: 0
Total transferred: 110500 bytes
HTML transferred: 21000 bytes
Requests per second: 65.23 [#/sec] (mean)
Time per request: 76.648 [ms] (mean)
Time per request: 15.330 [ms] (mean, across all concurrent requests)
Transfer rate: 14.08 [Kbytes/sec] received
2.opcache啓用,cache_list未配置
Concurrency Level: 5
Time taken for tests: 1.406 seconds
Complete requests: 500
Failed requests: 0
Total transferred: 110500 bytes
HTML transferred: 21000 bytes
Requests per second: 355.62 [#/sec] (mean)
Time per request: 14.060 [ms] (mean)
Time per request: 2.812 [ms] (mean, across all concurrent requests)
Transfer rate: 76.75 [Kbytes/sec] received
3.opcache未啓用,cache_list配置
Concurrency Level: 5
Time taken for tests: 7.588 seconds
Complete requests: 500
Failed requests: 0
Total transferred: 110500 bytes
HTML transferred: 21000 bytes
Requests per second: 65.89 [#/sec] (mean)
Time per request: 75.881 [ms] (mean)
Time per request: 15.176 [ms] (mean, across all concurrent requests)
Transfer rate: 14.22 [Kbytes/sec] received
4.opcache啓用,cache_list配置
Concurrency Level: 5
Time taken for tests: 1.312 seconds
Complete requests: 500
Failed requests: 0
Total transferred: 110500 bytes
HTML transferred: 21000 bytes
Requests per second: 381.01 [#/sec] (mean)
Time per request: 13.123 [ms] (mean)
Time per request: 2.625 [ms] (mean, across all concurrent requests)
Transfer rate: 82.23 [Kbytes/sec] received
測試結果看
1.啓用opcache後,對性能提升非常明顯。
7.665 -> 1.406
7.588 -> 1.312
2.啓用phar.cache_list後:對性能有一點點的提升。
7.665 -> 7.588
1.406 -> 1.312
來此加密:Let’s Encrypt 網頁版本,獲取SSL網站證書:https://letsencrypt.osfipin.com/。
所以最爲通用的做法是使用opcache。