在 CentOS 7 搭建好 LAMP 後,透過 PHP Opcode 快取 (Xcache) 與分散式記憶體快取 (Memcached) 可大幅降低資料庫負載、提升回應速度。本文記錄原始碼安裝 Xcache 3.2.0、yum 安裝 Memcached 及 PHP 擴充、WordPress 整合與 Gzip 壓縮啟用全流程。
cd /tmp
wget https://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz
tar xzf xcache-3.2.0.tar.gz
cd xcache-3.2.0
yum install -y php-devel gcc
phpize
./configure --enable-xcache
make && make install
cp xcache.ini /etc/php.d/
systemctl restart httpd
驗證:php -m | grep -i xcache 或建立 phpinfo() 頁面查看 Xcache 區塊。
yum install -y memcached
systemctl enable --now memcached
# 預設監聽 127.0.0.1:11211,記憶體 64MB
# 調整 /etc/sysconfig/memcached:
# PORT="11211"
# USER="memcached"
# MAXCONN="1024"
# CACHESIZE="128" # MB
# OPTIONS="-l 127.0.0.1"
yum install -y php-pecl-memcache
# 或原始碼編譯最新版
wget https://pecl.php.net/get/memcache-3.0.8.tgz
tar xzf memcache-3.0.8.tgz
cd memcache-3.0.8
phpize
./configure
make && make install
echo "extension=memcache.so" > /etc/php.d/memcache.ini
systemctl restart httpd
建立 memtest.php:
<?php
$mem = new Memcache;
$mem->connect('127.0.0.1', 11211) or die("Connect failed");
echo "Version: " . $mem->getVersion() . "\n";
$obj = new stdClass;
$obj->str = 'test'; $obj->int = 123;
$mem->set('key', $obj, false, 10) or die("Set failed");
echo "Stored.\n";
var_dump($mem->get('key'));
?>
瀏覽器訪問,顯示版本號與物件內容即正常。
wget https://downloads.wordpress.org/plugin/memcached.2.0.2.zip
unzip memcached.2.0.2.zip
cp memcached/object-cache.php /var/www/html/wp-content/
# WordPress 會自動偵測並使用 object-cache.php
編輯 /etc/httpd/conf/httpd.conf 末尾加入:
DeflateCompressionLevel 9
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/x-httpd-php
AddOutputFilter DEFLATE js css
systemctl restart httpd
curl -I -H "Accept-Encoding: gzip,deflate" https://localhost/
# 應見 Content-Encoding: gzip
三劍客合體,WordPress 輕鬆應付高流量。