在项目中,对于一些查询比较频繁的数据可以使用缓存,以加速响应,减少数据库查询。本篇文章说说 redis 作为驱动的缓存系统。清除缓存,Clear Cache, body = 在项目中,对于一些查询比较频繁的数据可以使用缓存,以加速响应,减少数据库查询。本篇文章说说 redis 作为驱动的缓存系统。
Redis 作为缓存驱动 首先安装 predis/predis:
1 composer require predis/predis
使用示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <?php namespace App \Http \Controllers ;use Illuminate \Http \Request ;use Illuminate \Support \Facades \Cache ;use Illuminate \Support \Facades \Redis ;class CacheController extends Controller { public function index ( ) { Cache ::put ('active_user_count' , 10 , 24 * 60 * 60 ); \cache ('active_user_count' , 10 , 24 * 60 * 60 ); Cache ::get ('active_user_count' , 0 ); \cache ('active_user_count' , 0 ); Cache ::get ('active_user_count' , function (){ return \Illuminate\Support\Facades\DB::select ('select count(*) from uses where active = 1' ); }); } public function redis ( ) { Redis ::sAdd ('sign:2023:user:1' , date ('Y-m-d' )); Redis ::sIsMemeber ('sign:2023:user:1' , date ('Y-m-d' )); Redis ::sCard ('sign:2023:user:1' ); } }
需要学习 Redis 相关知识。
清除缓存 使用 Artisan 命令行工具 1 2 3 4 5 6 7 8 9 10 11 # 清除所有缓存 php artisan cache:clear # 清除路由缓存 php artisan route:clear # 清除配置缓存 php artisan config:clear # 清除编译的视图缓存 php artisan view:clear
通过浏览器删除缓存 1 2 3 4 Route ::get ('/clear-cache' , function() { $exitCode = Artisan ::call ('cache:clear' ); return 'Application cache has been cleared' ; });
访问示例:http://127.0.0.1:8000/clear-cache
Demo:https://github.com/hefengbao/laravel-demo