在 CentOS 的 LNMP 环境中,建议分层集成缓存:Nginx 层、PHP 层、对象缓存层(Redis/Memcached)、数据库层(MySQL 缓冲池)。下面给出可直接落地的配置步骤与要点。
一、整体架构与缓存层次
二、Nginx 层缓存配置
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Proxy-Cache $upstream_cache_status;
}
location /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public";
}
}
}
http {
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=php_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_cache php_cache;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
}
}
}
systemctl restart nginx php-fpmcurl -I http://example.com,应看到 X-Proxy-Cache: HIT/MISS。三、PHP 层缓存配置
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
yum install php-apcu(或 pecl 安装),在 php.ini 启用:[apcu]
extension=apcu.so
apcu.enable_cli=1
apcu.shm_size=32M
systemctl restart php-fpm四、对象缓存层 Redis 或 Memcached
yum install -y redis
systemctl enable --now redis
yum install php-redis 或 pecl install redis && echo "extension=redis.so" >> /etc/php.d/redis.iniphp -m | grep redis<?php
$r = new Redis();
$r->connect('127.0.0.1', 6379);
$r->set('k','v', 3600);
var_dump($r->get('k'));
yum install -y memcached
systemctl enable --now memcached
yum install -y php-pecl-memcached # 推荐,扩展名为 memcached
# 或 yum install -y php-pecl-memcache # 扩展名为 memcache
systemctl restart php-fpm
<?php
$m = new Memcached();
$m->addServer('127.0.0.1', 11211);
$m->set('k','v', 600);
echo $m->get('k');
五、数据库层与监控优化
[mysqld]
innodb_buffer_pool_size=1G
innodb_buffer_pool_instances=8
query_cache_type=1
query_cache_size=64M
systemctl restart mysqldredis-cli info 查看命中率、内存与连接数。memcached-tool 127.0.0.1:11211 stats 查看命中率与 evictions。phpinfo() 或 php -m 确认 opcache/redis/memcached 已加载。六、实践建议与注意事项