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

Commit

Permalink
## [0.18.0] - 2020-02-21
Browse files Browse the repository at this point in the history
### Add
- Add `RedisCache`
  • Loading branch information
문정기 committed Feb 21, 2020
1 parent 43700c6 commit 55ac2c9
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [0.18.0] - 2020-02-21
### Add
- Add `RedisCache`

## [0.17.6] - 2020-02-20
### Add
- Add Function `getQueueAttributes` and Dto `SqsQueueAttributeDto` in `SqsService`
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"ext-json": "*",
"mailgun/mailgun-php": "^2.8.1",
"symfony/http-foundation": "^2.8.50|^3.4.26|^4.3",
"firebase/php-jwt": "^4.0|^5.0"
"firebase/php-jwt": "^4.0|^5.0",
"predis/predis": "^1.1"
},
"autoload": {
"psr-4": {
Expand Down
62 changes: 62 additions & 0 deletions lib/Cache/RedisCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);

namespace Ridibooks\Platform\Common\Cache;

use Predis\Client;

class RedisCache
{
/** @var Client|null */
private $client;

public function __construct(string $host, int $port = 6379)
{
try {
$this->client = new Client(['scheme' => 'tcp', 'host' => $host, 'port' => $port,]);
} catch (\Exception $e) {
$this->client = null;
trigger_error($e->getMessage());
}
}

public function get(string $key): ?string
{
try {
if ($this->client !== null) {
return $this->client->get($key);
}
} catch (\Exception $e) {
trigger_error($e->getMessage());
if ($this->client !== null && !$this->client->isConnected()) {
$this->client->connect();
}
}

return null;
}

public function setJson(string $key, array $value, int $ttl): void
{
$this->set($key, json_encode($value), $ttl);
}

public function set(string $key, string $value, int $ttl): void
{
try {
if ($this->client !== null) {
// setnx()은 호출 시점에서 해당하는 key-value가 존재하지 않는 경우에만 set이 성공한다.
// set 성공 시 return 1, 실패 시 return 0
$result = $this->client->setnx($key, $value);
if ($result === 1) {
$this->client->expire($key, $ttl);
}
}
} catch (\Exception $e) {
trigger_error($e->getMessage());
if ($this->client !== null && !$this->client->isConnected()) {
$this->client->connect();
}
}
}
}

0 comments on commit 55ac2c9

Please sign in to comment.