在 Ubuntu + ThinkPHP 环境下,优化缓存可以从 缓存驱动选择、服务器配置、代码层面、系统层面 几个方向来做。下面以 ThinkPHP 5 / 6 为例,给你一套实用方案。
比文件缓存快很多,适合高并发。
安装 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,
],
],
];
✅ 优点:
如果只能用文件:
'default' => 'file',
优化方式:
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
sudo mkdir /mnt/cache
sudo mount -t tmpfs tmpfs /mnt/cache -o size=256M
配置 ThinkPHP:
'path' => '/mnt/cache',
❌ 不要无限缓存
✅ 根据业务设 TTL
Cache::set('user_1', $data, 3600);
✅ 好:
Cache::get('article_' . $id);
❌ 差:
Cache::get('all_articles');
Cache::tag('article')->set('a1', $data);
Cache::tag('article')->clear();
⚠️ MySQL 8 已移除
User::cache(true, 60)->find(1);
location ~ \.php$ {
fastcgi_cache cache_php;
fastcgi_cache_valid 200 10m;
}
适合内容型网站。
redis-cli info memory
redis-cli monitor
✅ Ubuntu + Redis + OPcache + ThinkPHP Cache ✅ 热点数据 Redis ✅ 模板编译缓存开启 ✅ 定时清理无效缓存
如果你愿意,可以告诉我:
我可以给你 针对性配置示例。