How To Clear Redis Cache In Laravel
Cache
- Introduction
- Configuration
- Driver Prerequisites
- Cache Usage
- Obtaining A Cache Instance
- Retrieving Items From The Cache
- Storing Items In The Cache
- Removing Items From The Enshroud
- The Cache Helper
- Cache Tags
- Storing Tagged Cache Items
- Accessing Tagged Enshroud Items
- Removing Tagged Cache Items
- Atomic Locks
- Driver Prerequisites
- Managing Locks
- Managing Locks Across Processes
- Adding Custom Enshroud Drivers
- Writing The Driver
- Registering The Driver
- Events
Introduction
Some of the data retrieval or processing tasks performed past your application could be CPU intensive or accept several seconds to consummate. When this is the instance, it is common to cache the retrieved data for a time so it can be retrieved chop-chop on subsequent requests for the same data. The cached data is normally stored in a very fast data store such equally Memcached or Redis.
Thankfully, Laravel provides an expressive, unified API for various cache backends, allowing you to take advantage of their blazing fast data retrieval and speed up your web application.
Configuration
Your awarding's enshroud configuration file is located at config/enshroud.php
. In this file, you may specify which cache driver you would like to exist used by default throughout your application. Laravel supports popular caching backends like Memcached, Redis, DynamoDB, and relational databases out of the box. In addition, a file based cache driver is bachelor, while array
and "null" cache drivers provide convenient enshroud backends for your automated tests.
The cache configuration file as well contains diverse other options, which are documented within the file, so make certain to read over these options. Past default, Laravel is configured to utilize the file
cache driver, which stores the serialized, cached objects on the server's filesystem. For larger applications, information technology is recommended that you use a more robust commuter such every bit Memcached or Redis. You may even configure multiple cache configurations for the same commuter.
Driver Prerequisites
Database
When using the database
cache commuter, you lot will need to set upwards a table to contain the cache items. Yous'll find an example Schema
declaration for the table below:
Schema :: create ( ' enshroud ' , function ( $table ) {
$tabular array -> string ( ' key ' ) -> unique ();
$table -> text ( ' value ' );
$table -> integer ( ' expiration ' );
});
Note
You lot may as well use thephp artisan cache:table
Artisan command to generate a migration with the proper schema.
Memcached
Using the Memcached driver requires the Memcached PECL parcel to be installed. You may list all of your Memcached servers in the config/enshroud.php
configuration file. This file already contains a memcached.servers
entry to become yous started:
' memcached ' => [
' servers ' => [
[
' host ' => env ( ' MEMCACHED_HOST ' , ' 127.0.0.one ' ),
' port ' => env ( ' MEMCACHED_PORT ' , 11211 ),
' weight ' => 100 ,
],
],
],
If needed, you may set the host
option to a UNIX socket path. If you do this, the port
option should exist prepare to 0
:
' memcached ' => [
[
' host ' => ' /var/run/memcached/memcached.sock ' ,
' port ' => 0 ,
' weight ' => 100
],
],
Redis
Before using a Redis cache with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the predis/predis
package (~1.0) via Composer. Laravel Sail already includes this extension. In addition, official Laravel deployment platforms such as Laravel Forge and Laravel Vapor have the PhpRedis extension installed by default.
For more than information on configuring Redis, consult its Laravel documentation folio.
DynamoDB
Earlier using the DynamoDB enshroud commuter, you must create a DynamoDB table to store all of the cached data. Typically, this table should exist named cache
. However, you should name the table based on the value of the stores.dynamodb.table
configuration value within your application's cache
configuration file.
This table should likewise take a cord sectionalization central with a proper name that corresponds to the value of the stores.dynamodb.attributes.key
configuration item inside your application'south cache
configuration file. By default, the division key should exist named key
.
Cache Usage
Obtaining A Enshroud Example
To obtain a enshroud store instance, you may use the Cache
facade, which is what we will use throughout this documentation. The Cache
facade provides convenient, terse access to the underlying implementations of the Laravel enshroud contracts:
<?php
namespace App\Http\Controllers;
apply Illuminate\Support\Facades\ Cache ;
class UserController extends Controller
{
/**
* Prove a list of all users of the awarding.
*
* @return Response
*/
public function index ()
{
$value = Cache :: get ( ' cardinal ' );
//
}
}
Accessing Multiple Cache Stores
Using the Cache
facade, yous may admission various cache stores via the store
method. The central passed to the shop
method should stand for to one of the stores listed in the stores
configuration assortment in your enshroud
configuration file:
$value = Cache :: store ( ' file ' ) -> get ( ' foo ' );
Enshroud :: store ( ' redis ' ) -> put ( ' bar ' , ' baz ' , 600 ); // 10 Minutes
Retrieving Items From The Cache
The Cache
facade's get
method is used to retrieve items from the cache. If the item does not exist in the cache, zero
will be returned. If yous wish, you lot may pass a second argument to the get
method specifying the default value you wish to be returned if the item doesn't exist:
$value = Enshroud :: get ( ' key ' );
$value = Cache :: get ( ' central ' , ' default ' );
You may even laissez passer a closure equally the default value. The upshot of the closure will be returned if the specified detail does non exist in the cache. Passing a closure allows you to defer the retrieval of default values from a database or other external service:
$value = Cache :: get ( ' fundamental ' , function () {
return DB :: table ( /* ... */ ) -> become ();
});
Checking For Item Beingness
The has
method may be used to make up one's mind if an item exists in the enshroud. This method volition also return fake
if the item exists only its value is null
:
if ( Cache :: has ( ' fundamental ' )) {
//
}
Incrementing / Decrementing Values
The increment
and decrement
methods may be used to adjust the value of integer items in the enshroud. Both of these methods accept an optional second argument indicating the amount by which to increment or decrement the item's value:
Cache :: increase ( ' key ' );
Cache :: increase ( ' key ' , $corporeality );
Enshroud :: decrement ( ' key ' );
Cache :: decrement ( ' cardinal ' , $amount );
Retrieve & Store
Sometimes you lot may wish to think an detail from the cache, but also store a default value if the requested detail doesn't exist. For example, you may wish to retrieve all users from the enshroud or, if they don't exist, recall them from the database and add them to the cache. You may do this using the Cache::remember
method:
$value = Cache :: remember ( ' users ' , $seconds , role () {
return DB :: table ( ' users ' ) -> get ();
});
If the particular does not exist in the cache, the closure passed to the remember
method volition exist executed and its event will be placed in the cache.
You may use the rememberForever
method to retrieve an item from the cache or shop information technology forever if it does not exist:
$value = Cache :: rememberForever ( ' users ' , office () {
return DB :: table ( ' users ' ) -> get ();
});
Retrieve & Delete
If you lot demand to remember an item from the cache and then delete the item, you may apply the pull
method. Similar the go
method, cypher
volition be returned if the detail does non be in the cache:
$value = Cache :: pull ( ' key ' );
Storing Items In The Cache
You may use the put
method on the Cache
facade to store items in the cache:
Cache :: put ( ' key ' , ' value ' , $seconds = 10 );
If the storage time is not passed to the put
method, the item will be stored indefinitely:
Cache :: put ( ' key ' , ' value ' );
Instead of passing the number of seconds every bit an integer, yous may also pass a DateTime
example representing the desired expiration time of the cached item:
Cache :: put ( ' fundamental ' , ' value ' , now () -> addMinutes ( 10 ));
Shop If Not Present
The add
method will merely add the item to the cache if it does non already exist in the cache store. The method will render true
if the item is actually added to the cache. Otherwise, the method will return imitation
. The add
method is an atomic operation:
Cache :: add ( ' key ' , ' value ' , $seconds );
Storing Items Forever
The forever
method may be used to store an detail in the cache permanently. Since these items volition not elapse, they must exist manually removed from the enshroud using the forget
method:
Enshroud :: forever ( ' cardinal ' , ' value ' );
Note
If you are using the Memcached driver, items that are stored "forever" may exist removed when the cache reaches its size limit.
Removing Items From The Cache
You may remove items from the enshroud using the forget
method:
Enshroud :: forget ( ' fundamental ' );
You may too remove items by providing a nada or negative number of expiration seconds:
Cache :: put ( ' key ' , ' value ' , 0 );
Cache :: put ( ' central ' , ' value ' , - 5 );
You may articulate the entire cache using the flush
method:
Cache :: flush ();
Warning
Flushing the enshroud does not respect your configured cache "prefix" and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications.
The Cache Helper
In addition to using the Cache
facade, yous may also use the global enshroud
part to retrieve and store data via the cache. When the enshroud
function is chosen with a single, cord argument, it volition return the value of the given key:
$value = cache ( ' key ' );
If y'all provide an assortment of key / value pairs and an expiration time to the office, it will shop values in the cache for the specified duration:
cache ([ ' key ' => ' value ' ], $ seconds );
cache ([ ' key ' => ' value ' ], now () -> addMinutes ( 10 ));
When the enshroud
office is called without any arguments, it returns an instance of the Illuminate\Contracts\Cache\Factory
implementation, allowing you to phone call other caching methods:
enshroud () -> recollect ( ' users ' , $seconds , part () {
return DB :: table ( ' users ' ) -> become ();
});
Notation
When testing call to the globalcache
role, you may utilise theEnshroud::shouldReceive
method only equally if y'all were testing the facade.
Enshroud Tags
Warning
Cache tags are not supported when using thefile
,dynamodb
, ordatabase
enshroud drivers. Furthermore, when using multiple tags with caches that are stored "forever", performance will be best with a driver such equallymemcached
, which automatically purges stale records.
Storing Tagged Enshroud Items
Cache tags allow you to tag related items in the cache and then flush all buried values that accept been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. Items stored via tags may non be accessed without also providing the tags that were used to store the value. For example, let'southward admission a tagged cache and put
a value into the cache:
Cache :: tags ([ ' people ' , ' artists ' ]) -> put ( ' John ' , $john , $seconds );
Cache :: tags ([ ' people ' , ' authors ' ]) -> put ( ' Anne ' , $anne , $seconds );
Accessing Tagged Cache Items
To call back a tagged cache detail, pass the same ordered listing of tags to the tags
method and and so telephone call the get
method with the key you wish to retrieve:
$john = Enshroud :: tags ([ ' people ' , ' artists ' ]) -> get ( ' John ' );
$anne = Cache :: tags ([ ' people ' , ' authors ' ]) -> get ( ' Anne ' );
Removing Tagged Enshroud Items
You may affluent all items that are assigned a tag or list of tags. For example, this argument would remove all caches tagged with either people
, authors
, or both. So, both Anne
and John
would be removed from the cache:
Cache :: tags ([ ' people ' , ' authors ' ]) -> flush ();
In contrast, this argument would remove simply cached values tagged with authors
, so Anne
would be removed, simply not John
:
Cache :: tags ( ' authors ' ) -> affluent ();
Atomic Locks
Alert
To employ this feature, your application must be using thememcached
,redis
,dynamodb
,database
,file
, orarray
cache commuter as your application's default enshroud driver. In addition, all servers must be communicating with the same central cache server.
Driver Prerequisites
Database
When using the database
enshroud driver, yous will need to setup a tabular array to contain your application's cache locks. You'll observe an case Schema
declaration for the table below:
Schema :: create ( ' cache_locks ' , office ( $tabular array ) {
$table -> string ( ' key ' ) -> chief ();
$tabular array -> string ( ' possessor ' );
$table -> integer ( ' expiration ' );
});
Managing Locks
Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. For case, Laravel Forge uses diminutive locks to ensure that merely one remote job is being executed on a server at a time. You may create and manage locks using the Cache::lock
method:
use Illuminate\Support\Facades\ Cache ;
$lock = Cache :: lock ( ' foo ' , x );
if ( $lock -> become ()) {
// Lock acquired for x seconds...
$lock -> release ();
}
The get
method also accepts a closure. Afterwards the closure is executed, Laravel volition automatically release the lock:
Cache :: lock ( ' foo ' ) -> get ( function () {
// Lock acquired indefinitely and automatically released...
});
If the lock is not available at the moment you asking information technology, you may instruct Laravel to look for a specified number of seconds. If the lock can not be acquired within the specified time limit, an Illuminate\Contracts\Cache\LockTimeoutException
will be thrown:
apply Illuminate\Contracts\Cache\ LockTimeoutException ;
$lock = Cache :: lock ( ' foo ' , ten );
try {
$lock -> block ( 5 );
// Lock acquired subsequently waiting a maximum of 5 seconds...
} catch ( LockTimeoutException $e ) {
// Unable to acquire lock...
} finally {
optional ($ lock ) -> release ();
}
The example in a higher place may be simplified past passing a closure to the block
method. When a closure is passed to this method, Laravel will attempt to acquire the lock for the specified number of seconds and will automatically release the lock in one case the closure has been executed:
Cache :: lock ( ' foo ' , 10 ) -> cake ( five , function () {
// Lock acquired afterward waiting a maximum of five seconds...
});
Managing Locks Beyond Processes
Sometimes, you may wish to larn a lock in one process and release it in some other process. For example, you may acquire a lock during a web request and wish to release the lock at the cease of a queued job that is triggered by that request. In this scenario, you should pass the lock's scoped "possessor token" to the queued job so that the job tin can re-instantiate the lock using the given token.
In the example below, we will acceleration a queued chore if a lock is successfully caused. In addition, we volition pass the lock's possessor token to the queued job via the lock's owner
method:
$podcast = Podcast :: find ( $id );
$lock = Cache :: lock ( ' processing ' , 120 );
if ( $lock -> become ()) {
ProcessPodcast :: dispatch ( $podcast , $lock -> owner ());
}
Within our application'southward ProcessPodcast
chore, we can restore and release the lock using the owner token:
Cache :: restoreLock ( ' processing ' , $this ->owner ) -> release ();
If you would like to release a lock without respecting its current owner, you may use the forceRelease
method:
Cache :: lock ( ' processing ' ) -> forceRelease ();
Adding Custom Enshroud Drivers
Writing The Driver
To create our custom enshroud driver, we first need to implement the Illuminate\Contracts\Cache\Store
contract. So, a MongoDB enshroud implementation might look something like this:
<?php
namespace App\Extensions;
use Illuminate\Contracts\Cache\ Store ;
course MongoStore implements Shop
{
public function get ( $key ) {}
public function many ( array $keys ) {}
public part put ( $key , $value , $seconds ) {}
public function putMany ( array $values , $seconds ) {}
public function increase ( $primal , $value = i ) {}
public role decrement ( $key , $value = 1 ) {}
public function forever ( $key , $value ) {}
public function forget ( $key ) {}
public function affluent () {}
public function getPrefix () {}
}
Nosotros only need to implement each of these methods using a MongoDB connexion. For an instance of how to implement each of these methods, have a look at the Illuminate\Enshroud\MemcachedStore
in the Laravel framework source lawmaking. One time our implementation is complete, nosotros can stop our custom driver registration by calling the Cache
facade'south extend
method:
Cache :: extend ( ' mongo ' , function ( $app ) {
return Cache :: repository ( new MongoStore );
});
Note
If you're wondering where to put your custom cache driver lawmaking, you could create anExtensions
namespace within yourapp
directory. However, keep in mind that Laravel does non have a rigid application structure and you are complimentary to organize your awarding co-ordinate to your preferences.
Registering The Driver
To register the custom cache driver with Laravel, we will utilise the extend
method on the Cache
facade. Since other service providers may endeavour to read cached values within their boot
method, we volition annals our custom driver within a booting
callback. By using the booting
callback, we can ensure that the custom driver is registered but before the boot
method is called on our application'south service providers but subsequently the register
method is chosen on all of the service providers. We will annals our booting
callback within the register
method of our application's App\Providers\AppServiceProvider
class:
<?php
namespace App\Providers;
use App\Extensions\ MongoStore ;
use Illuminate\Back up\Facades\ Cache ;
use Illuminate\Back up\ ServiceProvider ;
form CacheServiceProvider extends ServiceProvider
{
/**
* Annals whatsoever application services.
*
* @return void
*/
public role annals ()
{
$this ->app-> booting ( function () {
Cache :: extend ( ' mongo ' , function ( $app ) {
render Cache :: repository ( new MongoStore );
});
});
}
/**
* Bootstrap whatever application services.
*
* @return void
*/
public office boot ()
{
//
}
}
The kickoff argument passed to the extend
method is the name of the driver. This will stand for to your driver
selection in the config/cache.php
configuration file. The second argument is a closure that should return an Illuminate\Enshroud\Repository
instance. The closure will be passed an $app
instance, which is an instance of the service container.
Once your extension is registered, update your config/cache.php
configuration file's commuter
selection to the name of your extension.
Events
To execute code on every cache performance, y'all may listen for the events fired by the enshroud. Typically, you should identify these outcome listeners within your awarding's App\Providers\EventServiceProvider
class:
employ App\Listeners\ LogCacheHit ;
utilise App\Listeners\ LogCacheMissed ;
apply App\Listeners\ LogKeyForgotten ;
use App\Listeners\ LogKeyWritten ;
use Illuminate\Enshroud\Events\ CacheHit ;
utilize Illuminate\Cache\Events\ CacheMissed ;
use Illuminate\Cache\Events\ KeyForgotten ;
utilize Illuminate\Cache\Events\ KeyWritten ;
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
CacheHit :: form => [
LogCacheHit :: grade ,
],
CacheMissed :: class => [
LogCacheMissed :: class ,
],
KeyForgotten :: class => [
LogKeyForgotten :: class ,
],
KeyWritten :: course => [
LogKeyWritten :: class ,
],
];
Source: https://laravel.com/docs/9.x/cache
0 Response to "How To Clear Redis Cache In Laravel"
Post a Comment