【转载】Laravel10.x 使用 Redis

发布时间 2023-11-23 16:46:37作者: 夏秋初

参考

环境

软件/系统 版本 说明
windows 10
php 8.1.9-Win32-vs16-x64
laravel ^10.10
redis Redis-x64-3.0.504
php_redis.dll php_redis-5.3.7-8.1-ts-vs16-x64 下载 (别的文章说版本要与当前php版本一致,其中nts与ts也要一致,否则开启扩展后也无法生效。)
php_igbinary.dll php_igbinary-3.2.7-8.1-ts-vs16-x64 下载 (别的文章说版本要与当前php版本一致,其中nts与ts也要一致,否则开启扩展后也无法生效。)

步骤

一、开启php扩展
  1. 将下载的 dll 放到当前使用的 php 目录中的 ext 目录下。
  2. 修改 php.ini 文件,开启扩展。
# 看别人文章说有顺序要求,先引入igbinary
extension=igbinary
extension=redis
  1. 重启 apache 生效配置。
二、将 Laravel .env 配置缓存类型为 redis
  1. 修改 .env 对应的配置
# 缓存类型
CACHE_DRIVER=redis
# redis 的ip、端口、密码
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

测试

一、使用 Cache 类

直接使用 cache 类操作,储存的内容都为序列化后的字符串。

use Illuminate\Support\Facades\Cache;
class TestController extends Controller
{
    public function index(Request $request)
    {
        Cache::set("first_key", ["123","123","123","123"]);
        dd(Cache::get("first_key"));
    }
}

二、使用 Redis 类

Laravel 使用魔术方法将命令传递给 Redis 服务器。

use Illuminate\Support\Facades\Redis;
class TestController extends Controller
{
    public function index(Request $request)
    {
        // phpinfo()
        Redis::rpush('first_key', '1');
        Redis::lpush('first_key', '2');
        dd(Redis::llen('first_key'));
    }
}