ubuntu

Ubuntu PHP配置缓存如何设置

小樊
41
2025-08-21 18:11:23
栏目: 编程语言

在Ubuntu上配置PHP缓存主要有以下两种方式,以下是具体步骤:

一、OPcache(PHP内置字节码缓存)

  1. 安装
    大多数Ubuntu PHP版本已默认包含OPcache,若未安装可执行:

    sudo apt update
    sudo apt install php-opcache  # 根据PHP版本选择对应包(如php7.4-opcache)
    
  2. 配置
    编辑PHP配置文件(根据Web服务器选择):

    • Apache: /etc/php/{version}/apache2/php.ini
    • PHP-FPM: /etc/php/{version}/fpm/php.ini
      取消注释并修改以下参数:
    [opcache]
    zend_extension=opcache.so
    opcache.enable=1
    opcache.memory_consumption=128  # 缓存内存大小(MB)
    opcache.max_accelerated_files=4000  # 缓存文件数量
    opcache.revalidate_freq=60  # 检查脚本更新频率(秒)
    
  3. 重启服务

    sudo systemctl restart apache2  # 或 php{version}-fpm
    

二、Redis/Memcached(外部缓存系统)

Redis配置

  1. 安装

    sudo apt update
    sudo apt install redis-server php-redis  # 安装Redis服务及PHP扩展
    sudo systemctl start redis-server
    
  2. 配置PHP使用Redis
    在代码中使用Redis类操作缓存,例如:

    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $redis->set('key', 'value', 3600);  // 缓存1小时
    

Memcached配置

  1. 安装

    sudo apt update
    sudo apt install memcached php-memcached
    sudo systemctl start memcached
    
  2. 配置PHP使用Memcached
    在代码中使用Memcached类,例如:

    $memcached = new Memcached();
    $memcached->addServer('127.0.0.1', 11211);
    $memcached->set('key', 'value', 3600);
    

三、验证配置

创建info.php文件(内容:<?php phpinfo(); ?>),访问该页面查看缓存模块是否启用。

说明

0
看了该问题的人还看了