Laravel 9 操作redis的方法
RedisUtil封装
<?php
namespace App\Utils;
use Illuminate\Support\Facades\Redis;
class RedisUtil
{
public static function setData($key, $value, $ex = 60)
{
$value = json_encode($value);
Redis::connection()->set($key, $value,"ex", $ex);
return true;
}
public static function getData($key)
{
$value = Redis::connection()->get($key);
$value = json_decode($value,true);
return $value ? $value : [];
}
public static function removeData($key)
{
return Redis::delete($key);
}
}
RedisUtil的使用
Redis指定键获取值
$key = "xxx";
$data = RedisUtil::getData($key);
Redis设置键值及过期时间
$key = "xxx";
RedisUtil::setData($key,$data,5*60);
Redis删除指定键
$key = "xxx";
Redis::delete($key);
$key = "xxx";
RedisUtil::delete($key);
Redis删除指定前缀的所有键
删除前
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0d5f6faa80f2674047195f116839cfb8.png)
$keys = Redis::keys("xxx:*");
RedisUtil::removeData($keys);
删除后
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e3727ab1effa3c9bf99dd940808044bb.png)