在Debian LNMP环境中,可通过以下方式使用缓存技术提升性能:
反向代理缓存:
编辑Nginx配置文件(如/etc/nginx/sites-available/default
),添加缓存路径及参数:
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 {
location / {
proxy_pass http://unix:/var/run/php/php7.4-fpm.sock;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
}
重启Nginx生效:sudo systemctl restart nginx
。
静态文件缓存:
对静态资源(如图片、CSS、JS)设置过期时间:
location ~* \.(jpg|jpeg|png|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
OPcache:
安装并启用OPcache扩展,编辑/etc/php/7.4/fpm/php.ini
:
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
重启PHP-FPM:sudo systemctl restart php7.4-fpm
。
Redis/Memcached:
sudo apt install redis-server php-redis
在PHP代码中使用:$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('key', 'value', 3600); // 缓存1小时
sudo apt install memcached php-memcached
配置后可在PHP中通过Memcached
类操作缓存。/etc/mysql/my.cnf
,调整缓冲池大小(建议为服务器内存的50%-80%):[mysqld]
innodb_buffer_pool_size=1G
innodb_buffer_pool_instances=8
重启MySQL:sudo systemctl restart mysql
。curl -I http://域名
查看响应头中是否有X-Proxy-Cache: HIT
。redis-cli
)或代码逻辑验证。max_size
、memory_consumption
)。/var/cache/nginx
),避免占用过多磁盘空间。以上配置可显著提升LNMP环境的响应速度和并发能力,具体参数需根据实际业务调整。