Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Commit

Permalink
feat(Cache): Allow ttl key for Redis Hash type
Browse files Browse the repository at this point in the history
  • Loading branch information
Rhilip committed Feb 26, 2020
1 parent c0aa627 commit 85a9587
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- **layout:** Add anti-robots html meta tag (9c21e73)

### Fix
- **API:** ApiMiddleware not work after change Response Component (6da82a7)
- **Bencode:** Fix dict keys may not in sorted order (81f0783)
- **Config:** Fix JSON type config return False (1129008)
- **Cron:** Fix components lost in CronTabProcess (1ced4bf)
Expand Down
18 changes: 13 additions & 5 deletions framework/Utils/ClassValueCacheUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,27 @@ protected function getCacheNameSpace(): string
}

// Get from class, redis cache, generate closure (may database) and then cache it in class and redis cache
final protected function getCacheValue($key, $closure)
final protected function getCacheValue(string $key, callable $closure, int $ttl = null)
{
if (!isset($this->$key)) {
$this->$key = app()->redis->hGet($this->getCacheNameSpace(), $key);
if (false === $this->$key) {
/** @var array $key_from_cache */
$key_from_cache = app()->redis->hGet($this->getCacheNameSpace(), $key);
if (false === $key_from_cache || ($key_from_cache['expire'] ?? -1) > time()) {
$this->$key = $closure();
app()->redis->hSet($this->getCacheNameSpace(), $key, $this->$key);
$cache = ['data' => $this->$key];
if (!is_null($ttl)) {
$cache['expire'] = time() + $ttl;
}
app()->redis->hSet($this->getCacheNameSpace(), $key, $cache);
} else {
$this->$key = $key_from_cache['data'];
}
}
return $this->$key;
}

final protected function removeCacheValue($key) {
final protected function removeCacheValue($key)
{
unset($this->$key);
app()->redis->hDel($this->getCacheNameSpace(), $key);
}
Expand Down

0 comments on commit 85a9587

Please sign in to comment.