LNMP缓存配置实战
一、整体思路与层级
二、Nginx缓存配置
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
location ~* \.html$ {
add_header Cache-Control "public, must-revalidate, max-age=600";
}
http {
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=my_fcgi_cache:10m max_size=1g inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_lock on;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 按实际版本与路径调整
fastcgi_cache my_fcgi_cache;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
add_header X-Cache $upstream_cache_status; # 便于观察命中:HIT/MISS/BYPASS
}
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_proxy_cache:10m max_size=1g inactive=60m use_temp_path=off;
}
server {
location / {
proxy_pass http://backend;
proxy_cache my_proxy_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
sudo nginx -t && sudo systemctl reload nginx三、PHP缓存配置
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=0 # 生产建议CLI关闭,避免开发/CLI与FPM行为不一致
[apcu]
extension=apcu.so
apcu.enable=1
apcu.shm_size=64M
apcu.ttl=7200
sudo systemctl restart php-fpm<?php phpinfo(); ?> 访问确认 opcache 与 apcu 模块已启用。四、数据库缓存配置
[mysqld]
# InnoDB缓冲池:建议为可用内存的 50%~70%(专用数据库服务器)
innodb_buffer_pool_size=1G
innodb_buffer_pool_instances=8
innodb_log_file_size=256M
innodb_log_buffer_size=16M
# 仅当确有需要再调整(如极端一致性场景),默认 1 更安全
innodb_flush_log_at_trx_commit=1
sudo systemctl restart mysqlSHOW ENGINE INNODB STATUS\G 与 SHOW VARIABLES LIKE 'innodb_buffer_pool%'; 检查状态与参数。五、应用层与CDN缓存
sudo apt-get update
sudo apt-get install memcached php-memcached
sudo systemctl enable --now memcached
-l 127.0.0.1
-p 11211
-m 64
-c 1024
<?php
$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);
$key = 'site:home';
$data = $memcached->get($key);
if (!$data) {
$data = build_expensive_data(); // 伪函数:从DB/API获取
$memcached->set($key, $data, 600); // 缓存 10 分钟
}
echo $data;
echo stats | nc 127.0.0.1 11211 查看命中率、内存占用与连接数,按业务调整 -m/-c 与缓存 TTL。sudo systemctl reload nginx && sudo systemctl restart php-fpm