Laravel 5.1 Redis缓存

Laravel 5.1 Redis cache

我正在尝试在我的 Laravel 应用程序中实施一个非常基本的缓存机制。

我安装了 Redis,通过终端 (src/redis-server) 启动它,并在 Laravel 的配置文件中将缓存从文件更改为 redis,但它比常规查询需要更长的时间(1 秒对 2 秒)当我使用缓存时。

我是不是漏掉了什么?我只想将查询缓存 10 分钟。

这是我的 FeedController.php

namespace App\Http\Controllers\Frontend\Feed;

use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Company;
use Redis;
use Cache;


class FeedController extends Controller
{

    public function index()
    {

        if (Cache::has('companies')) {
            // cache exists.
            $companies = Cache::get("companies");
        } else {
            // cache doesn't exist, create a new one
            $companies = Cache::remember("companies",10, function() {
                return Company::all();
            });

            Cache::put("companies", $companies, 10);
        }


        return view('index')->with('companies', $companies)
    }

我的观点

@foreach($companies as $company)
    {{$company->name}}
@endforeach

首先,缓存并不总是更快。其次,您正在仔细检查缓存。

您可以只使用:

$companies = Cache::remember("companies",10, function() {
            return Company::all();
        });

检查缓存项是否存在,如果不存在则执行闭包并将结果缓存到指定的key中。 cache:has if/else 是不必要的,只会减慢速度。