在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
,調整緩沖池大?。ńㄗh為服務器內存的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
)或代碼邏輯驗證。memory_consumption
)。/var/cache/nginx
),避免占用過多磁盤空間。以上配置可顯著提升LNMP環境的響應速度和并發能力,具體參數需根據實際業務調整。