centos

centos lnmp如何配置缓存策略

小樊
46
2025-07-10 20:29:09
栏目: 智能运维

在CentOS上配置LNMP(Linux, Nginx, MySQL, PHP)的缓存策略,可以显著提高网站的性能和响应速度。以下是一些常见的缓存策略配置方法:

1. Nginx 缓存配置

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;
            add_header X-Proxy-Cache $upstream_cache_status;
        }
    }
}

FastCGI缓存

编辑Nginx配置文件,添加或修改以下内容:

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;

    server {
        listen 80;
        server_name example.com;

        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_cache my_fcgi_cache;
            fastcgi_cache_valid 200 302 10m;
            fastcgi_cache_valid 404 1m;
            fastcgi_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
            add_header X-FastCGI-Cache $upstream_cache_status;
        }
    }
}

2. PHP 缓存配置

PHP 提供了多种缓存扩展,如 OPcache、APCu 和 Memcached。

OPcache

编辑PHP配置文件(通常是 /etc/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
opcache.fast_shutdown=1

APCu

编辑PHP配置文件,添加或修改以下内容:

[apcu]
extension=apcu.so
apcu.enable_cli=1
apcu.shm_size=32M
apcu.ttl=7200
apcu.user_ttl=7200
apcu.gc_ttl=3600

Memcached

首先安装Memcached和PHP的Memcached扩展:

sudo yum install memcached php-pecl-memcached

然后编辑PHP配置文件,添加或修改以下内容:

[memcached]
extension=memcached.so
memcached.sess_consistency=0
memcached.sess_lock_wait=1000
memcached.sess_lock_maxwait=1500

3. MySQL 缓存配置

MySQL 提供了查询缓存和InnoDB缓冲池等缓存机制。

查询缓存

编辑MySQL配置文件(通常是 /etc/my.cnf/etc/mysql/my.cnf),添加或修改以下内容:

[mysqld]
query_cache_type=1
query_cache_size=64M
query_cache_limit=2M

InnoDB缓冲池

编辑MySQL配置文件,添加或修改以下内容:

[mysqld]
innodb_buffer_pool_size=1G
innodb_buffer_pool_instances=8
innodb_log_file_size=256M
innodb_log_buffer_size=64M
innodb_flush_log_at_trx_commit=2
innodb_flush_method=O_DIRECT

4. 其他缓存策略

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public";
}

通过以上配置,你可以有效地提高LNMP环境的性能和响应速度。根据具体需求和服务器资源,调整缓存策略的参数。

0
看了该问题的人还看了