Home >PHP Framework >Laravel >Detailed explanation of the configuration and use of redis in laravel
The following tutorial column of Laravel Framework will give you a detailed explanation of the configuration and use of redis in laravel. I hope it will be helpful to friends in need! Configuration and use of redis in laravel
Introduce redis
composer require predis/predis
will introduce the latest version of predis in composer.json
composer update
Add the downloaded predis library to the vendor. After the command is executed successfully, as shown in the figure:
If you also have predis in your project directory, then the introduction is successful, congratulations!
Configuring redis
When it comes to the configuration of redis in laravel, in fact, the relevant configuration is already available in the default project, but it is not used by default. The default used is:
Project | Using type |
---|---|
CACHE_DRIVER | file |
SESSION_DRIVER | file |
Add redis database usage
'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], 'session' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 1, ], ],
The laravel project has relevant configurations by default (if you have not modified the default installation parameters of redis), you can also make relevant modifications based on the redis you installed and configured. The relevant parameters are also easy to understand.
Use redis for caching
The file used by default is used for caching. It is also very simple to modify it. Just modify the configuration parameters in the .env file directly and it will be OK.
Find the CACHE_DRIVER parameter and change
CACHE_DRIVER=file
to
CACHE_DRIVER=redis
Find the SESSION_DRIVER parameter and change
SESSION_DRIVER=file
to
SESSION_DRIVER=redis
Note: redis has been added to the aliases array in app/config/app.php, so it is very simple to use.
We can call any command provided by the Redis client (Redis command list) as a static method on the Redis facade, and then Laravel uses magic methods to pass the command to the Redis server and return the obtained results.
The simplest usage example:
// use 一下redis use Illuminate\Support\Facades\Redis; class IndexController extends Controller { public function useRedis() { Redis::set('foo', 2); echo Redis::get('foo'); } }
The output result is: 2
This is the end of the basic introduction, in-depth use will be continued.
The above is the detailed content of Detailed explanation of the configuration and use of redis in laravel. For more information, please follow other related articles on the PHP Chinese website!