萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

LAMP 架構下安裝 Xcache 與 Memcached 加速 WordPress

在 CentOS 7 搭建好 LAMP 後,透過 PHP Opcode 快取 (Xcache) 與分散式記憶體快取 (Memcached) 可大幅降低資料庫負載、提升回應速度。本文記錄原始碼安裝 Xcache 3.2.0、yum 安裝 Memcached 及 PHP 擴充、WordPress 整合與 Gzip 壓縮啟用全流程。

1. 安裝 Xcache (PHP Opcode Cache)

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 區塊。

2. 安裝 Memcached 服務端與 PHP 擴充

服務端

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"

PHP 擴充 (pecl memcache)

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

3. 測試 Memcached 運作

建立 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'));
?>

瀏覽器訪問,顯示版本號與物件內容即正常。

4. WordPress 整合 Memcached

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

5. 啟用 Apache Gzip/Deflate 壓縮

編輯 /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

效能提升預期

  • Xcache:PHP 編譯一次,後續請求直接執行 opcode,CPU 降 30-50%。
  • Memcached:熱門查詢、Session、物件快取命中,MySQL QPS 大幅下降。
  • Gzip:傳輸量減 70-80%,首屏載入加快。

三劍客合體,WordPress 輕鬆應付高流量。

copyright © 萬盛學電腦網 all rights reserved