温馨提示×

CentOS怎样配置PHP缓存

小樊
37
2026-07-08 03:09:42
栏目: 编程语言

在 CentOS 上配置 PHP 缓存,通常指两类缓存:

  1. PHP 字节码缓存(OPcache) ✅(最常用、必配)
  2. 应用层缓存(如 Redis / Memcached)(用于会话、数据缓存)

下面按常见场景详细说明。


一、配置 PHP OPcache(推荐必开)

OPcache 用于缓存 PHP 编译后的字节码,能显著提升性能。

1️⃣ 确认 PHP 已安装

php -v

常见版本:

  • CentOS 7:PHP 5.4 / 7.x(Remi 源)
  • CentOS 8/Stream:PHP 7.x / 8.x

2️⃣ 安装 OPcache

✅ PHP 7.x / 8.x(Remi 源)

yum install php-opcache -y

✅ CentOS 7 + Remi PHP

yum install yum-utils
yum-config-manager --enable remi-php81
yum install php-opcache

3️⃣ 配置 OPcache

编辑 PHP 配置文件(路径可能不同):

php --ini | grep "Loaded Configuration"

常见路径:

/etc/php.ini
/etc/php.d/10-opcache.ini

推荐配置(生产环境)

[opcache]
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0
opcache.revalidate_freq=0
opcache.fast_shutdown=1

⚠️ 开发环境建议:

opcache.validate_timestamps=1
opcache.revalidate_freq=2

4️⃣ 重启 PHP 服务

PHP-FPM

systemctl restart php-fpm

Apache + mod_php

systemctl restart httpd

5️⃣ 验证 OPcache 是否生效

php -i | grep opcache.enable

或在 PHP 文件中:

<?php
phpinfo();

二、配置 Redis 作为 PHP 缓存(可选)

1️⃣ 安装 Redis

yum install redis -y
systemctl enable redis
systemctl start redis

2️⃣ 安装 PHP Redis 扩展

yum install php-pecl-redis -y
systemctl restart php-fpm

3️⃣ PHP 中使用 Redis 示例

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('test', 'hello redis');
echo $redis->get('test');

三、配置 Memcached(可选)

安装

yum install memcached -y
yum install php-pecl-memcached -y
systemctl start memcached

四、常见优化建议

✅ 必做:

  • 开启 OPcache
  • 生产环境关闭 validate_timestamps

✅ 推荐:

  • 使用 PHP-FPM
  • 使用 Unix Socket 连接 Redis
  • 调整 pm.max_children

五、常见问题

❓ 修改后不生效?

  • 确认重启了 php-fpm
  • 确认修改的是正确的 php.ini

❓ OPcache 与 Redis 冲突吗?

✅ 不冲突,作用不同:

  • OPcache:加速 PHP 执行
  • Redis:缓存业务数据

如果你愿意,可以告诉我:

  • CentOS 版本
  • PHP 版本
  • Web 服务(Apache / Nginx)

我可以给你一套完全适配你环境的配置方案

0