Laravel 5.5 Cache

Cache(缓存)

// 缓存使用
    (获取缓存实例)
        * 访问多个缓存存储
            $value = Cache::store('file')->get('foo');
            Cache::store('redis')->put('bar', 'baz', 10);
    
    (从缓存中获取数据)
        $value = Cache::get('key');
        $value = Cache::get('key', 'default');
        $value = Cache::get('key', function() {
            return DB::table(...)->get();
        });

        * 检查缓存项是否存在
            if (Cache::has('key')) {
                // 如果值为 null 或 false 该方法会返回 false
            }
    
        * 数值增加/减少
            Cache::increment('key');
            Cache::increment('key', $amount);
            Cache::decrement('key');
            Cache::decrement('key', $amount);
    
        * 获取&存储
            有时候你可能想要获取缓存项,但如果请求的缓存项不存在时给它存储一个默认值。例如,你可能想要从缓存中获取所有用户,或者如果它们不存在的话,从数据库获取它们并将其添加到缓存中,你可以通过使用 Cache::remember 方法实现:
            $value = Cache::remember('users', $minutes, function() {
                return DB::table('users')->get();
            });
    
            $value = Cache::rememberForever('users', function() {
                return DB::table('users')->get();
            });
    
        * 获取&删除
            如果你需要从缓存中获取缓存项然后删除,你可以使用 pull 方法
            $value = Cache::pull('key');
    
    (在缓存中存储数据)
        Cache::put('key', 'value', $minutes);  // 在缓存中存储数据

        $expiresAt = Carbon::now()->addMinutes(10);
        Cache::put('key', 'value', $expiresAt);  // 传递一个代表缓存项有效时间的 PHP Datetime 实例

        * 缓存不存在时存储数据
            Cache::add('key', 'value', $minutes);
    
        * 永久存储数据
            forever 方法用于持久化存储数据到缓存,这些值必须通过 forget 方法手动从缓存中移除:
            Cache::forever('key', 'value');
    
    (从缓存中移除数据)
        Cache::forget('key');
        Cache::flush();  // 清除所有缓存
    
    (缓存辅助函数)
        * 存储
            $value = cache('key');
    
        * 获取
            cache(['key' => 'value'], $minutes);
            cache(['key' => 'value'], Carbon::now()->addSeconds(10));

// 缓存标签
    (存储被打上标签的缓存项)
        Cache::tags(['people', 'artists'])->put('John', $john, $minutes);
        Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);
    
    (访问被打上标签的缓存项)
        $john = Cache::tags(['people', 'artists'])->get('John');
        $anne = Cache::tags(['people', 'authors'])->get('Anne');
    
    (移除被打上标签的数据项)
        Cache::tags(['people', 'authors'])->flush();
        Cache::tags('authors')->flush();

猜你喜欢

转载自blog.csdn.net/qq_37910492/article/details/84546624