Files
hyperf_service/app/Cache/Redis/Api/SiteCache.php
2025-02-26 10:53:06 +08:00

71 lines
1.8 KiB
PHP

<?php
namespace App\Cache\Redis\Api;
use App\Cache\Redis\Common\CommonRedisKey;
use App\Cache\Redis\RedisCache;
use App\Constants\RedisCode;
use App\Model\Site;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class SiteCache
{
/**
* @var RedisCache
*/
#[Inject]
protected RedisCache $redis;
/**
* @var Site
*/
#[Inject]
protected Site $siteModel;
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function setSiteRedis()
{
$siteKey = CommonRedisKey::siteListKey();
$LngLatKey = CommonRedisKey::siteLngLatKey();
if ($this->redis->exists($siteKey) && $this->redis->exists($LngLatKey)) return;
$siteList = $this->siteModel->getAllSiteList();
$this->redis->delete($siteKey);
$this->redis->delete($LngLatKey);
foreach ($siteList as $site) {
$this->redis->geoAdd($LngLatKey, $site['lng'],$site['lat'],$site['id'],RedisCode::SYSTEM_DB);
}
$this->redis->set($siteKey,json_encode(array_column($siteList, null, 'id'), JSON_UNESCAPED_UNICODE),RedisCode::SYSTEM_DB);
}
/**
* @param int $siteId
* @return array|null
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function getSiteInfo(int $siteId): array|null
{
$this->setSiteRedis();
$siteKey = CommonRedisKey::siteListKey();
$siteListJsonDecode = json_decode($this->redis->get($siteKey,RedisCode::SYSTEM_DB), true);
if (empty($siteListJsonDecode)) return null;
$siteList = array_column($siteListJsonDecode, null, 'id');
unset($siteListJsonDecode);
return $siteList[$siteId] ?? null;
}
}