【问题标题】:How to use Redis cache in Laravel?如何在 Laravel 中使用 Redis 缓存?
【发布时间】:2020-01-18 21:55:32
【问题描述】:

这是我第一次使用 Laravel 和 Redis。我了解如何在终端上获取、设置 Redis 等。但不知道如何在 Laravel 应用程序上应用 Redis。 我有使用 MVC 模式将参与者的信息保存在数据库中的应用程序。我想将其更改为使用 Redis 缓存以使其更快(并用于练习)。我需要做什么? 你能用代码解释一下吗?

这是参与者控制器。 “编辑”功能将用户发送到编辑页面,用户编辑信息并按下“保存”,激活“更新”功能。 store/updateUserInput 函数只是将数据保存到数据库中。

   /**
     * Show the form for editing the specified participant.
     *
     * @param int $id
     * @return View
     */
    public function edit(int $id): View
    {
        $participant = Participant::find($id);
        if(empty($participant)){
            return view('errors.404');
        }
        return view('participants.edit', ['participant'=>$participant]);
    }

    /**
     * Update the specified participant in storage.
     *
     * @param ParticipantValidation $request
     * @return RedirectResponse
     */
    public function update(ParticipantValidation $request): RedirectResponse
    {
        $participant = Participant::find($request->id);
        if(empty($participant)){
            return view('errors.404');
        }
        $detail = $request->all();
        Participant::updateUserInput($detail);
        return redirect()->route('participants.create', $detail['event_id'])->with('success', 'Updated!');
    }

+加上我在“控制器”上尝试使用此代码以使用 $redis->set('message', 'Hello world'); 之类的东西,但出现错误,他们找不到“Predis/Autoload.php”

require 'Predis/Autoload.php';
PredisAutoloader::register();

try {
    $redis = new PredisClient();
}
catch (Exception $e) {
    die($e->getMessage());
}

【问题讨论】:

    标签: php laravel caching redis predis


    【解决方案1】:

    你可以使用缓存门面

    在您的 .env 文件中,您必须添加 CACHE_DRIVER=redis

    然后,无论何时您想获取 Participant 的实例:

    $participant = null;
    $key ="Participant".$id;
    if(Cache::has($key)//get participant from cache
        $participant = Cache::get($key);
    else{//get participant and cache for 3 minutes
        $participant = Participant::find($id);
        $seconds = 180;
        Cache::set($key, $participant, $seconds);
    }
    

    【讨论】:

    • 这个可以大大简化为$participant = Cache::remember('participant_' . $id, 180, function () use($id) { return Participant::find($id); });
    • 病了!我不会想到添加一个闭包作为默认值
    • $participant = Cache::remember("participant_$id", 180, fn() => Participant::find($id));
    猜你喜欢
    • 2017-05-24
    • 2020-04-03
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2019-04-01
    • 2020-07-13
    • 2020-06-29
    相关资源
    最近更新 更多