使用Laravel操作Redis

目录

Laravel的文章列表如下,介绍了PHP框架Laravel的使用方法。

Laravel版本

动作确认是在Laravel Framework 7.19.1版本上进行的。

只需要一种选择前提条件

使用Eclipse搭建Laravel开发环境。可以设置断点进行调试(无论是Windows、Vagrant还是docker)。本文假设上述步骤已经完成,并进行了项目创建和Apache配置。

在Laravel中使用DI
本文将使用上述创建的文件夹和文件

安装PhpRedis

通过PhpRedis操作Redis。
通过以下链接完成环境设置的人应该已经安装了。
通过超简单的步骤搭建LAMP+Redis环境。
如果还没有安装,请按照下面的链接进行安装phpredis。

设置

(1)/sample/.env文件修正
编写用于访问Redis的配置

‥‥
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
‥‥

请将REDIS_HOST、REDIS_PASSWORD、REDIS_PORT的值更改为适合您的环境。
如果您在vagrant的转发端口设置中更改了端口,请将其更改为适合您的环境的值。

(2)/sample/config/database.php修改
在database.php中使用了在.env中定义的Redis连接配置
修改’redis’ => ‘default’元素为’redis’ => ‘db2’,并添加’redis’ => ‘db2’元素

‥‥
'redis' => [
‥‥
        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'db2' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => '2',
        ],
‥‥

我创建了两个连接到Redis的定义。

(3)在/sample/config/app.php修正中,将aliases要素内的Redis注释掉。

‥‥
//'Redis' => Illuminate\Support\Facades\Redis::class,
‥‥

创建服务类

在/sample/app/Services/Interfaces文件夹中创建RedisService.php。

<?php
namespace App\Services\Interfaces;

interface RedisService
{
    public function __construct();

    public function setKey1($value);
    public function getKey1();

}

(2) 在/sample/tests/Services/Impl文件夹中创建RedisServiceImpl.php。

<?php
namespace Tests\Services\Impl;

use App\Services\Interfaces\RedisService;

class RedisServiceImpl implements RedisService
{

    public function __construct()
    {
    }

    public function setKey1($value)
    {
    }

    public function getKey1()
    {
    }

}

在/sample/app/Services/Impl文件夹中创建RedisServiceImpl.php。

<?php
namespace App\Services\Impl;

use App\Services\Interfaces\RedisService;
use Illuminate\Support\Facades\Redis;

class RedisServiceImpl implements RedisService
{

    private $redis = null;

    public function __construct()
    {
        $this->redis = Redis::connection('db2');
    }

    public function setKey1($value)
    {
        Redis::set('key1', 'default_' . $value);
        $this->redis->set('key1', 'db2_' . $value);
    }

    public function getKey1()
    {
        $default = Redis::get('key1');
        $db2 = $this->redis->get('key1');

        return [$default, $db2];

    }

}

如果以静态函数的方式编写类似于Redis::set的代码,则会使用之前在database.php中写的默认连接。
如果要使用其他连接,请明确获取连接,例如Redis::connection(‘db2’)。
Redis类的方法名可以直接使用Redis命令名。

注册DI

(1) 在 /sample/app/Providers/DiServiceProvider.php 文件中添加以下内容:
“`php
use App\Services\Interfaces\RedisService;
“`

在/sample/app/Providers/DiServiceProvider.php的register方法中追加以下代码:
app()->singleton(RedisService::class, $prefix . ‘RedisServiceImpl’);

DiServiceProvider.php是使用Laravel的DI(依赖注入)创建的文件。
在Laravel中使用DI,已经将其注册在config/app.php的providers中。

添加方法到控制器

(1) 在 /sample/app/Http/Controllers/SampleController.php 文件中添加 use 语句
use App\Services\Interfaces\RedisService;

(2) 在/sample/app/Http/Controllers/SampleController.php中添加redis1方法和redis2方法。

    public function redis1(Request $request, RedisService $redisService)
    {
        $key1Value = $request->input('key1');

        if (!is_null($key1Value)) {
            $redisService->setKey1($key1Value);
        }

        return view('sample.redis1');

    }

    public function redis2(RedisService $redisService)
    {
        $key1Value = $redisService->getKey1();

        $data = ['key1Value' => var_export($key1Value, true)];

        return view('sample.redis2', $data);
    }

(3)在/sample/routes/web.php中添加以下内容:
Route::get(‘sample/redis1’, ‘SampleController@redis1’);
Route::get(‘sample/redis2’, ‘SampleController@redis2’);

创建视图

(1) 创建 /sample/resources/views/sample/redis1.blade.php 文件。

<html>
    <head>
        <title>sample</title>
    </head>
    <body>

        <form action="{{ url('sample/redis1') }}" method="get">
            <div>key1<input type="text" name="key1" value=""></div>
            <input type="submit" >
        </form>

    </body>
</html>

(2)创建/sample/resources/views/sample/redis2.blade.php文件。

<html>
    <head>
        <title>sample</title>
    </head>
    <body>

        <div>{{$key1Value}}</div>

    </body>
</html>

1. 确认操作动作

a.png
b.png

我来查一下 Redis。

127.0.0.1:6379> select 0
OK
127.0.0.1:6379> keys *
1) "laravel_database_key1"

保存的时候带有 “laravel_database_” 这个前缀是因为在 config/database.php 的 redis=>options=>prefix 元素中设置了前缀。

127.0.0.1:6379[2]> select 0
OK
127.0.0.1:6379> get laravel_database_key1
"default_value1"
127.0.0.1:6379> select 2
OK
127.0.0.1:6379[2]> get laravel_database_key1
"db2_value1"
127.0.0.1:6379[2]>

我们可以看到Redis中也存有值。

将session存储在Redis中。

(1) 修改/sample/.env配置文件
填写会话设置

‥‥
#SESSION_DRIVER=file
SESSION_DRIVER=redis
SESSION_CONNECTION=db2
‥‥

将SESSION_DRIVER更改为redis。在SESSION_CONNECTION中指定存储位置的Redis连接。

进行动作确认2

让我们使用Laravel的会话功能。访问上面文章中创建的链接:http://localhost/laravelSample/sample/session1。

我来看一下Redis。

127.0.0.1:6379[2]> select 2
OK
127.0.0.1:6379[2]> keys *
1) "laravel_database_laravel_cache:xxxxxxxxxxxxxxxxxxxxxx"

可以看出他已经登录到了Redis中。

bannerAds