Files
hyperf_service/app/Cache/Redis/Common/ConfigCache.php
2025-03-04 15:41:51 +08:00

104 lines
2.8 KiB
PHP

<?php
namespace App\Cache\Redis\Common;
use App\Cache\Redis\RedisCache;
use App\Constants\ConfigCode;
use App\Constants\RedisCode;
use App\Model\Config;
use App\Model\Cycle;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Tappable\HigherOrderTapProxy;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class ConfigCache
{
/**
* @var RedisCache
*/
#[Inject]
protected RedisCache $redis;
/**
* @var Config $configModel
*/
#[Inject]
protected Config $configModel;
/**
* @param $pid
* @return array|mixed
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function setConfigCacheByPid($pid): mixed
{
$key = CommonRedisKey::getSystemConfigListByPid($pid);
if ($this->redis->exists($key,RedisCode::SYSTEM_DB)) return json_decode($this->redis->get($key,RedisCode::SYSTEM_DB),true);
$data = $this->configModel->where('pid', $pid)->pluck('value','key')->toArray();
if (empty($data)) return [];
$this->redis->set($key,json_encode($data),RedisCode::SYSTEM_DB);
return $data;
}
/**
* @param $key
* @return mixed|string
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function getConfigValue($key): mixed
{
$arr = $this->setConfigCache();
return $arr[$key] ?? '';
}
/**
* @param $key
* @param int $isRedis
* @param int $expire
* @return false|HigherOrderTapProxy|mixed|\Redis|string
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function getConfigValueByKey($key, int $isRedis = 0,int $expire = 600): mixed
{
$redisKey = CommonRedisKey::getConfigKey($key);
if (!$this->redis->exists($redisKey,RedisCode::SYSTEM_DB)) {
$value = $this->configModel->where('key',$key)->value('value');
if ($isRedis == 1) {
$this->redis->setEx($redisKey, $value, $expire,RedisCode::SYSTEM_DB);
}
return $value ?? ConfigCode::DEFAULT_VALUE[$key];
}
return $this->redis->get($redisKey,RedisCode::SYSTEM_DB) ?? ConfigCode::DEFAULT_VALUE[$key];
}
/**
* @return array|mixed
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function setConfigCache(): mixed
{
$key = CommonRedisKey::getSystemConfigList();
if ($this->redis->exists($key,RedisCode::SYSTEM_DB)) return json_decode($this->redis->get($key,RedisCode::SYSTEM_DB),true);
$data = $this->configModel->pluck('value','key')->toArray();
if (empty($data)) return [];
$this->redis->set($key,json_encode($data),RedisCode::SYSTEM_DB);
return $data;
}
}