Home  >  Article  >  Database  >  How to use laravel redis cache

How to use laravel redis cache

王林
王林forward
2023-06-03 09:52:39918browse

Step 1: Install Redis

First, you need to install Redis on the server. On Ubuntu, you can install it through the following command:

sudo apt-get update
sudo apt-get install redis-server

If you are using another operating system, you can download the relevant documents from the Redis official website for installation.

Step 2: Configure Laravel

To use Redis cache in an application, you need to make relevant configurations in Laravel's configuration file first. Open the config/cache.php file, find the line 'default' => env('CACHE_DRIVER', 'file'), and modify it to:

'default' => env('CACHE_DRIVER', 'redis'),

Next, you need to add the Redis configuration. Find the line 'stores' => [ and add the following content:

'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
],

In 'connections' => [ Add the following content:

'default' => [
        'host'     => env('REDIS_HOST', '127.0.0.1'),
        'port'     => env('REDIS_PORT', 6379),
        'database' => env('REDIS_DB', 0),
        'password' => env('REDIS_PASSWORD', null),
 ],

Here, we configure the default Redis connection, using parameters such as host, port, database and password. These parameters can be adjusted according to the configuration of Redis on the server. Revise.

Step 3: Use Redis cache

We have completed the configuration of Redis and can now start using Redis cache in Laravel. In Laravel, caching operations can be performed in the following ways:

// 获取缓存值
$value = Cache::get('key');

// 存储缓存
Cache::put('key', 'value', $minutes);

// 存储永久缓存
Cache::forever('key', 'value');

// 判断缓存是否存在
if (Cache::has('key')) {
    //
}

// 删除缓存
Cache::forget('key');

// 清空所有缓存
Cache::flush();

It should be noted that when using Redis cache, the parameter $minutes is the number of minutes to cache. If you need to store a permanent cache, you can use the forever method.

In Laravel, you can also set the cache expiration time in the following ways:

// 设置缓存有效期为 5 分钟
Cache::put('key', 'value', 5);

// 设置缓存有效期为 10 分钟
Cache::add('key', 'value', 10);

If you need to customize the cache prefix, you can 'stores' => [ Add the following to:

'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'prefix' => 'my_custom_cache_prefix',
],

This way, all cache keys will be prefixed with my_custom_cache_prefix:.

The above is the detailed content of How to use laravel redis cache. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete