laravel8. 75. The use of cache supports redis and Memcache drivers

Procedural apes are fearless 2022-02-13 05:15:25 阅读数:132

laravel8. laravel use cache supports

To configure

The cache configuration file is located at config/cache.php. In this file , You can specify which cache driver to use by default .Laravel Supported cache backend includes Memcached、Redis、DynamoDB, And ready-made relational databases . Besides , It also supports file based cache drivers , And a cache driver that facilitates automated testing array、null. The default cache driver is file.

Cache usage

Get cache instance

To get the cache storage instance , have access to Cache facade.Cache facade Provide for the right to Laravel The convenience of the underlying implementation of cache contract 、 Concise access :

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Cache;
class UserController extends Controller

/** * Displays a list of all users of the application . * * @return Response */
public function index()

$value = Cache::get('key');

Access multiple cache stores

Use Cache facade, Can pass store Method to access various cache stores . Pass to store The key of the method should be the same as cache In profile stores One of the storage listed in the configuration array corresponds to :

$value = Cache::store('file')->get('foo');
Cache::store('redis')->put('bar', 'baz', 600); // 10 Minutes

Retrieve items from cache

Cache facade Of get Method to retrieve an item from the cache . If the item does not exist in the cache , Then return to null. If you like , You can pass the second parameter to get Method , Specifies the default value returned when the item does not exist :

$value = Cache::get('key');
$value = Cache::get('key', 'default');

You can even pass closures as defaults . If the specified item does not exist in the cache , The result of closing will be returned . Passing closures allows you to delay retrieving default values from databases or other external services :

$value = Cache::get('key', function () {

return DB::table(...)->get();

Check whether the cache item exists

Use has Method to determine whether a cache item exists in the cache . If the cache entry exists but is null This method also returns false:

if (Cache::has(‘key’)) {

Increasing / Decreasing value

increment and decrement Method is used to change the value of the shaping item in the cache . The second parameter received by the two methods is an optional parameter , This parameter is used to indicate the value to be incremented or decremented :

Cache::increment('key', $amount);
Cache::decrement('key', $amount);

Get and store

Sometimes you may want to get a data from the cache , When the requested item does not exist , A default value is stored . for example , You may want to get all users from the cache , But when these users do not exist in the cache , The program takes the user out of the database and puts it into the cache . You can use Cache::remember Method realization :

$value = Cache::remember('users', $seconds, function () {

return DB::table('users')->get();

If the cache data does not exist , that remember The closure of the method will be executed , Then return the result and put it in the cache .

You can use rememberForever Method to get data from the cache or permanently store data that does not exist in the cache :

$value = Cache::rememberForever('users', function () {

return DB::table('users')->get();

Get and delete

If you need to get data from the cache , Then delete it , have access to pull Method . and get The method is the same , If the cache does not exist , Then return to null:

$value = Cache::pull('key');

Store data in cache

You can use Cache Facade Of put Method stores the data in the cache :

Cache::put('key', 'value', $seconds = 10);

If you don't tell put The duration of method storage , Then the data will be stored permanently .

Cache::put('key', 'value');

In addition to the number of seconds to pass the shaping , You can also pass a DateTime The instance of represents the expiration time of cached data :

Cache::put('key', 'value', now()->addMinutes(10));

Store only data that you don't have

add Method only adds data that does not exist in the cache to the cache . If the storage is successful, this method returns true conversely , return false.add The method is the operation of atomization :

Cache::add('key', 'value', $seconds);

Data is stored permanently

forever Method can be used to persist data in the cache . Because these data will not expire , They have to use forget Method to manually delete :

Cache::forever('key', 'value');

skill : If you use Memcached drive , When the cached data reaches the storage limit ,「 Permanent storage 」 Your data may be deleted .

Delete data from cache

You can use forget Method to delete the data from the cache :


You can also delete this data by providing zero or negative expiration seconds :

Cache::put('key', 'value', 0);
Cache::put('key', 'value', -5);

You can use flush Method to empty all cached data :


Be careful : The method of emptying the cache does not consider the cache prefix , All contents in the cache will be deleted . Therefore, when clearing the cache shared with other applications , Please think carefully about .

Cache Auxiliary function

Except that it can be used Cache facade , You can also use global helper functions cache To get and save cached data . When only one string parameter is used to call cache Function time , The value corresponding to the given key will be returned .

$value = cache('key');

If you provide a set of key value pairs with expiration time to the function , So in this period of time , It will cache this data :

cache(['key' => 'value'], $seconds);
cache(['key' => 'value'], now()->addMinutes(10));

When cache The function is called without any arguments , Then it will return an implementation Illuminate\Contracts\Cache\Factory Example , And allows you to call other caching methods :

cache()->remember('users', $seconds, function () {

return DB::table('users')->get();

skill : If you use global functions in your tests cache , You can use Cache::shouldReceive The method is like testing the facade.

Cache tags

Be careful : When using file,dynamodb or database Cache driven , Cache tags will not support . Besides , When using multiple with 「 permanent 」 When storing cached tags , It's best to use a driver that automatically clears stale records for example Memcached For optimal performance .

Store tagged cache data

Cache tag allows you to tag the relevant cache tag items with the same tag so that these cache values can be cleared later . You can access these cache entries by passing in a carefully arranged array of tags . for example , We can use... While using labels put Method to set the cache .

Cache::tags(['people', 'artists'])->put('John', $john, $seconds);
Cache::tags(['people', 'authors'])->put('Anne', $anne, $seconds);

Access tagged cache data

To get a tagged cache data , Pass an ordered array of the same tags to tags Method , And then call get The way to retrieve your key :

$john = Cache::tags(['people', 'artists'])->get('John');
$anne = Cache::tags(['people', 'authors'])->get('Anne');

Remove cached data with labels

You may need to remove all cached data marked by a single tag or a group of tags , for example , The following example will remove the with people,authors Or all cached data for both tags , therefore Anne and John Will be deleted from the cache :

Cache::tags(['people', 'authors'])->flush();

contrary , The following example will only remove the tag authors Cache data , therefore Anne Cached data will be removed , however John Won't :

copyright:author[Procedural apes are fearless],Please bring the original link to reprint, thank you.