120 lines
2.7 KiB
PHP
Executable File
120 lines
2.7 KiB
PHP
Executable File
<?php
|
||
|
||
namespace App\Service\common;
|
||
|
||
use Illuminate\Support\Facades\Redis;
|
||
|
||
class RedisService
|
||
{
|
||
|
||
private static mixed $_instance;
|
||
|
||
private $prefix = 'default';
|
||
|
||
private $redis;
|
||
|
||
/**
|
||
* 获取实例
|
||
* @return null|static
|
||
*/
|
||
public static function getInstance(): null|static
|
||
{
|
||
$name = get_called_class();
|
||
if (!isset(self::$_instance[$name])) {
|
||
self::$_instance[$name] = new static();
|
||
}
|
||
|
||
return self::$_instance[$name];
|
||
}
|
||
|
||
/**
|
||
* 初始化
|
||
* @param string $prefix
|
||
* @return RedisService
|
||
*/
|
||
public function init(string $prefix = 'default'): static
|
||
{
|
||
$this->redis = Redis::class;
|
||
$this->prefix = $prefix;
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* 设置缓存
|
||
* @param $key
|
||
* @param $value
|
||
* @param int $expire
|
||
* @return true
|
||
*/
|
||
public function set($key, $value, int $expire = 0): true
|
||
{
|
||
$this->redis::set($this->prefix . $key, $value);
|
||
if ($expire > 0) {
|
||
$this->redis::expire($this->prefix . $key, $expire);
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 累加
|
||
* @param $key
|
||
* @param int $value
|
||
* @param int $expire
|
||
* @return true
|
||
*/
|
||
public function incr($key, int $value = 1, int $expire = 0): true
|
||
{
|
||
$this->redis::incr($this->prefix . $key, $value);
|
||
if ($expire > 0) {
|
||
$this->redis::expire($this->prefix . $key, $expire);
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 获取缓存
|
||
*
|
||
* @param $key
|
||
* @return mixed
|
||
*/
|
||
public function get($key): mixed
|
||
{
|
||
return $this->redis::get($this->prefix . $key);
|
||
}
|
||
|
||
/**
|
||
* 删除缓存
|
||
* @param $key
|
||
* @return bool
|
||
*/
|
||
public function del($key): bool
|
||
{
|
||
return $this->redis::del($this->prefix . $key);
|
||
}
|
||
|
||
/**
|
||
* 清空当前前缀下的全部键
|
||
*
|
||
* 菜单这类按角色分片缓存的数据,改了菜单树要一次性失效所有角色的副本。
|
||
* KEYS 的返回值带着 redis 客户端自身的 prefix,直接回传给 del 会二次拼前缀,所以要先剥掉。
|
||
* @return int 删除的键数量
|
||
*/
|
||
public function delAll(): int
|
||
{
|
||
$keys = $this->redis::keys($this->prefix . '*');
|
||
if (empty($keys)) {
|
||
return 0;
|
||
}
|
||
$clientPrefix = (string) config('database.redis.options.prefix');
|
||
$count = 0;
|
||
foreach ($keys as $key) {
|
||
if ($clientPrefix !== '' && str_starts_with($key, $clientPrefix)) {
|
||
$key = substr($key, strlen($clientPrefix));
|
||
}
|
||
$this->redis::del($key);
|
||
$count++;
|
||
}
|
||
return $count;
|
||
}
|
||
}
|