【Laravel Cache】 配置redis 存储缓存,通俗易懂,一次就掌握

1. 配置缓存 /config/cache.php

配置缓存驱动是什么?(即 CACHE_DRIVER=“stores 中的key”)

配置stores中具体的模块

配置缓存key值的前缀(即 CACHE_PREFIX)

return [
'default' => env('CACHE_DRIVER', 'file'),

'stores' => [
		....省略内容....
        'redis' => [
            'driver' => 'redis',
            'connection' => 'cache',  # 对应 config/database.php 中的redis.cache 内容
        ],
		....省略内容....

    ],
 # 配置前缀地址
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
];

2. 配置redis,即配置 config/database.php

'redis' => [

    ....省略内容....
    
	# 配置此项,连接redis 服务器
    'cache' => [   
        'url' => env('REDIS_URL'),
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => env('REDIS_CACHE_DB', 1),  # redis 数据库 1   redis-cli > select 1
    ],

],

至此,根据上述内容,我们知道了 cache 使用redis 存储的过程之后,把对应配置项写入的 .env 环境配置中
执行php artisan config:cache --env=<环境名称> 即可

3. 使用Cache

use Illuminate\Support\Facades\Cache;

# 简单使用
# 添加
  # 返回值:Boolean
  # 只会在缓存项不存在的情况下添加缓存项到缓存,如果缓存项被添加到缓存返回true,否则,返回false
  # 60 为过期时间 60秒
  Cache::add('key', 'value', 60); # 60秒
  
  # 缓存中存储缓存项的时候,你需要指定数据被缓存的时间(分钟数)
  Cache::put('key', 'value', 5); # 5分钟
  
  # 持久化
  Cache::forever('key', 'value');

# 获取
$value = Cache::get('key');

4. 高级操作,加锁

说明:只有 redis、memcached、dynamodb可以使用加锁操作

if (Cache::has($cacheKey)) {
    
    
	$res = Cache::get($cacheKey);
    Log::info("{
      
      $cacheKey} is existed!!");
    return $res;
}
$res = Cache::lock($cacheKey)->get(function () use ($params) {
    
    
    // 获取无限期锁并自动释放...
    # 执行业务逻辑
    return self::sendGetRequest($params);
});
$isAddSuccess = Cache::add($cacheKey, $res, 1 * 60);
Log::info("{
      
      $cacheKey}{
      
      $isAddSuccess}");

猜你喜欢

转载自blog.csdn.net/qq_22227087/article/details/110134251