使用 Redis 在 Laravel 中缓存:简单示例

使用 Redis 缓存是 Laravel 职位描述中的常见要求之一。但这并不复杂,本教程将向您展示基础知识。

下面是一个关于如何在 Laravel 中使用 Redis 缓存 Eloquent 查询的简单教程。


1. Redis 服务器:安装/启动

Redis 不是 Laravel 专用系统,它是单独安装的,只需按照其官方安装说明即可。

然后,只需使用命令启动它。redis-server


2. 安装 Redis PHP 扩展

确保您已安装 Redis PHP 扩展:

对于基于 Ubuntu 的系统:

sudo apt-get install redis php8.1-redis
sudo systemctl restart php8.1-fpm.service

3. 安装 Predis 软件包

Predis 是一个灵活且功能齐全的 PHP Redis 客户端。通过 Composer 安装它:

composer require predis/predis

4. 在 Laravel 中配置 Redis

将文件中的 to 更改为:CACHE_STOREredis.env

CACHE_STORE=redis

如果不使用默认值,请编辑文件以更改 Redis 服务器配置:.env

REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

5. 在 Laravel 中使用 Redis 进行缓存

5.1 缓存雄辩的查询

假设您有一个 Eloquent 查询,如下所示:

$users = User::where('active', 1)->get();

要使用 Redis 缓存此查询结果,请执行以下操作:

use Illuminate\Support\Facades\Cache;
 
$users = Cache::remember('active_users', 60, function () {
    return User::where('active', 1)->get();
});

这里,是缓存键,是缓存结果的秒数,当找不到缓存时,闭包会获取用户。'active_users'60

5.2 清除缓存

要清除缓存的结果,请执行以下操作:

use Illuminate\Support\Facades\Cache;
 
Cache::forget('active_users');

6. 显示缓存数据

下面是一个使用缓存显示活动用户的简单示例:

  1. 在以下位置创建路由 :web.php
use Illuminate\Support\Facades\Cache;
use App\Models\User;
 
Route::get('/active-users', function () {
    $users = Cache::remember('active_users', 60, function () {
        return User::where('active', 1)->get();
    });
 
    return view('active_users', ['users' => $users]);
});
  1. 创建视图:active_users.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Active Users</title>
</head>
<body>
    <h1>Active Users</h1>
    <ul>
        @foreach($users as $user)
            <li>{{ $user->name }}</li>
        @endforeach
    </ul>
</body>
</html>

现在,当您在浏览器中访问时,它将从数据库中获取并显示活动用户,并将结果缓存 60 秒。/active-users


7.检查当前缓存

如果您想查看当前缓存了哪些值,可以使用名为 RedisInsight 的工具来完成。

Was this helpful?

0 / 0

发表回复 0