温馨提示×

ubuntu thinkphp怎么优化缓存

小樊
48
2026-10-13 10:33:55
栏目: 编程语言

在 Ubuntu + ThinkPHP 环境下,优化缓存可以从 缓存驱动选择、服务器配置、代码层面、系统层面 几个方向来做。下面以 ThinkPHP 5 / 6 为例,给你一套实用方案。


一、选择更快的缓存驱动(最重要)

1️⃣ 使用 Redis(强烈推荐)

比文件缓存快很多,适合高并发。

安装 Redis(Ubuntu)

sudo apt update
sudo apt install redis-server
sudo systemctl enable redis
sudo systemctl start redis

ThinkPHP 配置

// config/cache.php
return [
    'default' => 'redis',
    'stores' => [
        'redis' => [
            'type' => 'redis',
            'host' => '127.0.0.1',
            'port' => 6379,
            'password' => '',
            'select' => 0,
            'timeout' => 0,
        ],
    ],
];

✅ 优点:

  • 内存级缓存
  • 支持集群
  • 支持过期、队列

2️⃣ 文件缓存(不推荐生产)

如果只能用文件:

'default' => 'file',

优化方式:

  • 放在 tmpfs(内存盘)
  • 减少缓存键数量

二、Ubuntu 系统级缓存优化

1️⃣ 开启 OPcache(PHP 加速)

sudo apt install php-opcache

编辑 php.ini:

opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60

重启 PHP:

sudo systemctl restart php-fpm
# 或
sudo systemctl restart apache2

2️⃣ 使用 tmpfs 加速文件缓存(可选)

sudo mkdir /mnt/cache
sudo mount -t tmpfs tmpfs /mnt/cache -o size=256M

配置 ThinkPHP:

'path' => '/mnt/cache',

三、ThinkPHP 代码层缓存优化

1️⃣ 合理设置缓存时间

❌ 不要无限缓存
✅ 根据业务设 TTL

Cache::set('user_1', $data, 3600);

2️⃣ 缓存粒度控制

  • 缓存「数据结果」而不是「整个页面」
  • 避免大数组缓存

✅ 好:

Cache::get('article_' . $id);

❌ 差:

Cache::get('all_articles');

3️⃣ 使用缓存标签(ThinkPHP 6)

Cache::tag('article')->set('a1', $data);
Cache::tag('article')->clear();

四、数据库查询缓存(减少 DB 压力)

MySQL 查询缓存(老版本)

⚠️ MySQL 8 已移除

替代方案

  • Redis 缓存 SQL 结果
  • 使用 ThinkPHP 模型缓存
User::cache(true, 60)->find(1);

五、Web 服务器缓存(Nginx)

Nginx 静态缓存

location ~ \.php$ {
    fastcgi_cache cache_php;
    fastcgi_cache_valid 200 10m;
}

适合内容型网站。


六、监控与调优

Redis 监控

redis-cli info memory
redis-cli monitor

PHP 性能

  • xhprof
  • tideways
  • opcache status

七、推荐组合(生产环境)

✅ Ubuntu + Redis + OPcache + ThinkPHP Cache ✅ 热点数据 Redis ✅ 模板编译缓存开启 ✅ 定时清理无效缓存


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

  • ThinkPHP 版本(5 / 6 / 8)
  • 是否高并发
  • 当前用的是文件还是 Redis

我可以给你 针对性配置示例。

0 踩