hyperf-chat/app/Cache/Repository/HashRedis.php

109 lines
2.1 KiB
PHP
Raw Normal View History

2021-05-20 16:53:34 +08:00
<?php
2021-08-28 16:11:38 +08:00
declare(strict_types=1);
2021-05-20 16:53:34 +08:00
namespace App\Cache\Repository;
use App\Cache\Contracts\HashRedisInterface;
/**
* Redis Hash
*
* @package App\Cache\Repository
*/
2021-05-21 22:56:42 +08:00
class HashRedis extends AbstractRedis implements HashRedisInterface
2021-05-20 16:53:34 +08:00
{
2021-05-21 22:56:42 +08:00
protected $prefix = 'rds-hash';
2021-05-20 16:53:34 +08:00
2021-05-21 22:56:42 +08:00
protected $name = 'default';
2021-05-20 16:53:34 +08:00
/**
* 获取 Hash
*
* @param string ...$key
* @return array|string
*/
public function get(string ...$key)
{
2021-05-21 17:43:41 +08:00
if (func_num_args() == 1) {
2021-05-21 22:56:42 +08:00
return (string)$this->redis()->hGet($this->getCacheKey(), $key[0]);
2021-05-20 16:53:34 +08:00
}
2021-05-21 22:56:42 +08:00
return $this->redis()->hMGet($this->getCacheKey(), $key);
2021-05-20 16:53:34 +08:00
}
/**
* 设置 Hash
*
2021-05-20 22:23:48 +08:00
* @param string $key
* @param string|int $value
2021-05-20 16:53:34 +08:00
*/
2021-05-20 22:23:48 +08:00
public function add(string $key, $value)
2021-05-20 16:53:34 +08:00
{
2021-05-21 22:56:42 +08:00
$this->redis()->hSet($this->getCacheKey(), $key, $value);
2021-05-20 16:53:34 +08:00
}
/**
* 删除 hash
*
* @param string ...$key
* @return bool|int
*/
public function rem(string ...$key)
{
2021-05-21 22:56:42 +08:00
return $this->redis()->hDel($this->getCacheKey(), ...$key);
2021-05-20 16:53:34 +08:00
}
/**
* 给指定元素累加值
*
* @param string $member 元素
* @param int $score
* @return float
*/
2021-08-28 16:11:38 +08:00
public function incr(string $member, int $score): float
2021-05-20 16:53:34 +08:00
{
2021-05-21 22:56:42 +08:00
return $this->redis()->hincrby($this->getCacheKey(), $member, $score);
2021-05-20 16:53:34 +08:00
}
/**
* 获取 Hash 中元素总数
*
* @return int
*/
2021-08-28 16:11:38 +08:00
public function count(): int
2021-05-20 16:53:34 +08:00
{
2021-05-21 22:56:42 +08:00
return (int)$this->redis()->hLen($this->getCacheKey());
2021-05-20 16:53:34 +08:00
}
/**
* 获取 Hash 中所有元素
*
* @return array
*/
2021-08-28 16:11:38 +08:00
public function all(): array
2021-05-20 16:53:34 +08:00
{
2021-05-21 22:56:42 +08:00
return $this->redis()->hGetAll($this->getCacheKey());
2021-05-20 16:53:34 +08:00
}
/**
* 判断 hash 表中是否存在某个值
*
* @param string $key
* @return bool
*/
2021-08-28 16:11:38 +08:00
public function isMember(string $key): bool
2021-05-20 16:53:34 +08:00
{
2021-05-21 22:56:42 +08:00
return $this->redis()->hExists($this->getCacheKey(), $key);
2021-05-20 16:53:34 +08:00
}
/**
* 删除 Hash
*
* @return bool
*/
2021-08-28 16:11:38 +08:00
public function delete(): bool
2021-05-20 16:53:34 +08:00
{
2021-05-21 22:56:42 +08:00
return (bool)$this->redis()->del($this->getCacheKey());
2021-05-20 16:53:34 +08:00
}
}