Laravel¿ª·¢£ºÔõÑùʹÓÃLaravel RedisʵÏÖÊý¾Ý»º´æ£¿
laravelÊÇÒ»¸öºÜÊÇÊ¢ÐеÄphp¿ò¼Ü£¬ÆÕ±éÓ¦ÓÃÓÚweb¿ª·¢¡£laravel¿ò¼ÜÌṩÁËÐí¶àÇáÓ¯µÄapiºÍ×é¼þ£¬ÆäÖаüÀ¨Êý¾Ý»º´æ¡£redisÊÇÊ¢ÐеĿªÔ´ÄÚ´æÊý¾Ý½á¹¹´æ´¢£¬¿ÉÒÔºÜÊÇÓÐÓõØÌá¸ßÊý¾ÝÅÌÎʺͶÁȡЧÂÊ¡£±¾ÎĽ«ÏÈÈÝÔõÑùÔÚlaravelÖÐʹÓÃlaravel redisʵÏÖÊý¾Ý»º´æ£¬ÒÔÌá¸ßwebÓ¦ÓóÌÐòµÄÐÔÄÜ¡£
×°ÖÃ
Ê×ÏÈ£¬ÎÒÃÇÐèҪװÖÃLaravel Redis¡£¿ÉÒÔͨ¹ýÔËÐÐÒÔÏÂÏÂÁîʹÓÃComposer×°Öãº
composer require predis/predis
µÇ¼ºó¸´ÖÆ
ʹÓÃpredis/predis°üʵÏÖLaravel Redis»º´æÇý¶¯³ÌÐò¡£Íê³É×°Öúó£¬ÐèÒªÔÚ.envÎļþÖÐÉèÖÃREDIS_HOST£¬REDIS_PASSWORDºÍREDIS_PORT±äÁ¿¡£
REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379
µÇ¼ºó¸´ÖÆ
ÉèÖÃLaravel Redis
ÐÞ¸Äconfig/cache.phpÎļþÖеÄÉèÖ㬽«’default’Ñ¡Ïî¸ü¸ÄΪ’redis’ʹÓÃRedis×÷Ϊ»º´æÇý¶¯¡£ÁíÍ⣬ÔÚ’redis’Êý×éÖÐÉèÖÃRedisÅþÁ¬ÐÅÏ¢¡£
'default' => env('CACHE_DRIVER', 'redis'), 'redis' => [ 'client' => 'predis', 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => env('REDIS_DB', 0), ], ],
µÇ¼ºó¸´ÖÆ
ʹÓÃLaravel Redis
Ò»µ©ÉèÖúÃÁËLaravel RedisµÄÇý¶¯³ÌÐòºÍÉèÖã¬ÎÒÃÇ¿ÉÒÔ×îÏÈʹÓÃËüÁË¡£ÏÂÃæÊÇͨ¹ýLaravel Redis¾ÙÐÐÊý¾Ý»º´æµÄ3ÖÖÒªÁ죺
ͨË×»º´æ
ʹÓÃLaravel RedisµÄ×î¼òÆÓÒªÁìÊÇʹÓÃCacheÃÅÃæµÄ»ù±¾ÒªÁì¡£Laravel¿ò¼ÜÌṩÁËÐí¶à¸ß¼¶¹¦Ð§£¬µ«ÕâÀïÇ¿µ÷×î»ù±¾µÄ»º´æ´¦ÀíÒªÁì¡£¿ÉÒÔͨ¹ýÒÔÏ´úÂë¾ÙÐлº´æ£º
use IlluminateSupportFacadesCache; $value = Cache::remember('key', $minutes, function () { return DB::table('users')->get(); });
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂ뽫Ч¹û´Ó”users”±íÖлº´æµ½RedisÖС£ÔÚ´ËÖ®ºó£¬Å²ÓøÃÃÜԿʱ½«Öظ´Ê¹ÓÃRedisÖеĻº´æ¸±±¾£¬¶ø²»ÊÇ´ÓÔ´Êý¾Ý¿âÖØÐÂÌìÉúЧ¹û¡£Cache::rememberÒªÁìµÄµÚ¶þ¸ö²ÎÊýÊÇ»º´æÓÐÓÃÆÚ£¨ÒÔ·ÖÖÓΪµ¥Î»£©£¬»òÕß¿ÉÒÔʹÓÃCache::foreverÒªÁ콫Êý¾ÝÓÀÊÀÉúÑĵ½»º´æÖС£
±êÇ©»º´æ
ÁíÒ»ÖÖʹÓÃLaravel RedisµÄ¸ß¼¶»º´æÒªÁìÊÇʹÓñêÇ©¡£±êǩʹÄú¿ÉÒÔ½¨ÉèºÍ²¶»ñ¶à¸ö»º´æÌõÄ¿£¬È»ºóʹÓñêǩɨ³ýËùÓÐÕâЩÌõÄ¿¡£±êÇ©»º´æÌṩÁ˶Իº´æÉúÃüÖÜÆڵĸüºÃ¿ØÖÆ¡£
use IlluminateSupportFacadesCache; Cache::tags(['people', 'artists'])->put('John', $john, $minutes); Cache::tags(['people', 'authors'])->put('Jane', $jane, $minutes);
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂ뽫JohnÉúÑÄÔÚÁ½¸ö±êÇ©peopleºÍartistsÖУ¬²¢½«JaneÉúÑÄÔÚÁ½¸ö±êÇ©peopleºÍauthorsÖС£ÏÖÔÚ¿ÉÒÔʹÓÃÌض¨±êÇ©µÄflushÒªÁ죬½öɨ³ý¸Ã±êǩϵÄËùÓлº´æÏî¡£
Cache::tags(['people'])->flush();
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëɨ³ýËùÓдøÓÐpeople±êÇ©µÄ»º´æ²¢½«ËüÃÇ´ÓRedisÖÐɾ³ý¡£
¸¨Öúº¯Êý
Laravel Redis»¹ÌṩÁËһЩ¹¦Ð§½ÏÉÙµ«Ê¹ÓÃÆðÀ´Ô½·¢Àû±ãµÄ¸¨Öúº¯Êý¡£ÒÔÏÂÊÇÆäÖÐһЩ£º
cache()->put(‘key’, ‘value’, $minutes) »º´æÊäÈëֵһ׼ʱ¼ä¡£
cache()->get(‘key’) ¼ìË÷ÒÑ»º´æµÄÖµ¡£
cache()->remember(‘key’, $minutes, function() { return ‘value’; }) ¼ìË÷Èκλº´æÏʧ°Üʱ·µ»ØÐÂÖµ¡£
cache()->rememberForever() ÓÀÔ¶¼Ç×Å»º´æÏî¡£
½áÓï
Laravel RedisÌṩÁËһЩ¼òÆÓÒ×ÓõÄÒªÁìÀ´»º´æÊý¾Ý£¬ÔÚWebÓ¦ÓóÌÐòÖÐʵÏÖ¸ßЧµÄÊý¾Ý¶ÁÈ¡ºÍÅÌÎÊ¡£Laravel¿ò¼ÜÏÕЩÍêÈ«ÓÉComposerÖ§³Ö£¬ÕâʹµÃʹÓÃLaravel Redis±äµÃºÜÈÝÒס£ÔÚ´óÐÍWebÓ¦ÓóÌÐòÉÏʹÓÃLaravel Redis»º´æµÄÀûÒæÔÚÓÚ£¬Ëü¿ÉÒÔïÔÌ´Ó½ÏÂýµÄÊý¾Ý¿âÆÌÕÅʱ¼ä£¬Ìá¸ß¶¯Ì¬Êý¾ÝµÄÅÌÎÊËÙÂÊ¡£
ÒÔÉϾÍÊÇLaravel¿ª·¢£ºÔõÑùʹÓÃLaravel RedisʵÏÖÊý¾Ý»º´æ£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡