在 Linux + Laravel 环境下,缓存可以分为 Laravel 应用层缓存 和 Linux 系统/服务层缓存。下面从常见、实用的角度给你系统讲一下。
编辑 .env 文件:
CACHE_DRIVER=file
常见驱动:
file(默认,最简单)redis(推荐,生产环境)memcacheddatabasearray(仅请求期间)查看当前配置:
php artisan config:cache
Cache::put('key', 'value', 600); // 600秒
$value = Cache::get('key');
Cache::forever('key', 'value');
Cache::forget('key');
php artisan route:cache
清理:
php artisan route:clear
php artisan config:cache
php artisan config:clear
php artisan view:cache
php artisan view:clear
sudo apt update
sudo apt install redis-server
启动:
sudo systemctl start redis
sudo systemctl enable redis
.env:
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
安装 PHP Redis 扩展:
sudo apt install php-redis
sudo systemctl restart php-fpm
测试:
php artisan tinker
Cache::put('test', 123, 60);
Cache::get('test');
sudo apt install php-opcache
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
重启 PHP:
sudo systemctl restart php-fpm
Linux 会自动缓存文件,无需手动干预。
查看内存缓存:
free -h
清理(不推荐频繁):
sudo sync && sudo echo 3 > /proc/sys/vm/drop_caches
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 30d;
access_log off;
}
如果你愿意,可以告诉我:
我可以给你一套 最优缓存方案。