在LNMP(Linux, Nginx, MySQL, PHP)環境下配置緩存可以顯著提高網站性能。以下是一些常見的緩存配置方法:
Nginx 提供了多種緩存機制,包括代理緩存和FastCGI緩存。
編輯 Nginx 配置文件(通常是 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/default.conf
),添加以下內容:
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://backend;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
}
同樣在 Nginx 配置文件中添加:
http {
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=php_fastcgi_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_cache php_fastcgi_cache;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
}
PHP 提供了多種緩存擴展,如 OPcache、APCu 和 Memcached。
OPcache 是 PHP 的內置擴展,用于緩存預編譯的字節碼。編輯 php.ini
文件,添加或修改以下內容:
[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
APCu 是一個用戶空間緩存擴展,適用于共享內存。編輯 php.ini
文件,添加或修改以下內容:
[apcu]
extension=apcu.so
apcu.enable_cli=1
apcu.shm_size=64M
apcu.ttl=7200
apcu.enable_hook=0
Memcached 是一個分布式內存對象緩存系統。首先安裝 Memcached 和 PHP 擴展:
sudo apt-get install memcached php-memcached
編輯 php.ini
文件,添加以下內容:
[memcached]
extension=memcached.so
memcached.sess_consistency=strong
memcached.sess_lock_wait=1000
memcached.sess_prefix=phpsess_
MySQL 提供了查詢緩存和 InnoDB 緩存池。
編輯 my.cnf
或 my.ini
文件,添加或修改以下內容:
[mysqld]
query_cache_type=1
query_cache_size=64M
編輯 my.cnf
或 my.ini
文件,添加或修改以下內容:
[mysqld]
innodb_buffer_pool_size=1G
innodb_log_file_size=256M
innodb_flush_log_at_trx_commit=2
innodb_flush_method=O_DIRECT
還可以使用 Redis 或 Memcached 作為應用層緩存。
安裝 Redis 和 PHP 擴展:
sudo apt-get install redis-server php-redis
在 PHP 代碼中使用 Redis:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('key', 'value');
echo $redis->get('key');
安裝 Memcached 和 PHP 擴展(如上所述),在 PHP 代碼中使用 Memcached:
$memcached = new Memcached();
$memcached->addServer('127.0.0.1', 11211);
$memcached->set('key', 'value');
echo $memcached->get('key');
通過以上配置,你可以在 LNMP 環境下有效地使用緩存來提高網站性能。根據具體需求選擇合適的緩存策略和工具。