使用 OPcache 提升 PHP 應用效能

Oct 8, 2016 PHP English

提升 PHP 應用效能有許多種方式,而使用 OPcache 算是一種簡單且有效的手段。因此,本篇將介紹如何在 PHP 5.6 環境下啟用與設定 OPcache。



啟用 OPcache

接下來的步驟將會在 PHP 容器中進行 (php:5.6.13-apache)。基本上,PHP 5.6 已經將 OPcache 內建了,因此我們不需要手動安裝它,只需要將它啟用即可。首先,找出 OPcache 所在位置:

# 進入 Docker container
docker exec -it <your-container-name> bash

# 找出 OPcache 所在路徑
find / -name "opcache.so"

將 OPcache 設定加入 php.ini (如:/usr/local/etc/php/php.ini) 檔案最後,範例如下:

# 省略部分內容 ...

# 加入 OPcache 相關參數
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20131226/opcache.so
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=5000
opcache.fast_shutdown=1
opcache.enable_cli=1
opcache.save_comments=0
# 於正式環境可以取消以下參數
opcache.revalidate_freq=60

為了確保 OPcache 能正常運作,別忘了重啟該容器。重啟容器指令:

docker restart <your-container-name>

重啟後,可以在容器內使用以下指令確認啟用是否成功:

# 查看 php 資訊
php -v

# 若啟用成功會出現 OPcache 相關資訊
PHP 5.6.13 (cli) (built: Sep 23 2015 19:47:17)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies


測試 OPcache

我使用 Apache HTTP server benchmarking tool (ab) 來測試 PHP 啟用 OPcache 後的效能。指令如下:

ab -n 10000 -c 20 http://your-app

測試結果如下:



你也可能會喜歡:




若對於文章內容有任何建議與指正,非常歡迎你告訴我或者與我一起討論 ! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.