Added Redis cache

This commit is contained in:
Pablo Ferreiro 2022-01-14 19:26:07 +01:00
parent b7563d3ee9
commit 282ad20a6b
No known key found for this signature in database
GPG key ID: 41FBCE65B779FA24
5 changed files with 53 additions and 3 deletions

View file

@ -0,0 +1,31 @@
<?php
namespace Helpers\CacheEngines;
use \Redis;
class RedisCache {
private \Redis $client;
function __construct(string $host, int $port, ?string $password) {
$this->client = new Redis();
$this->client->connect($host, $port);
if ($password) {
$this->client->auth($password);
}
}
function __destruct() {
$this->client->close();
}
public function get(string $cache_key): object|false {
if ($this->client->exists($cache_key)) {
$data_string = $this->client->get($cache_key);
return json_decode($data_string);
}
return false;
}
public function set(string $cache_key, mixed $data, $timeout = 3600) {
$this->client->set($cache_key, json_encode($data), $timeout);
}
}

View file

@ -1,7 +1,9 @@
<?php
namespace Helpers;
use Exception;
use Helpers\CacheEngines\JSONCache;
use Helpers\CacheEngines\RedisCache;
use Helpers\Settings;
class Misc {
@ -28,6 +30,17 @@ class Misc {
case 'json':
$cacheEngine = new JSONCache();
break;
case 'redis':
if (!isset($_ENV['REDIS_URL'])) {
throw new Exception('You need to set REDIS_URL to use Redis Cache!');
}
$url = parse_url($_ENV['REDIS_URL']);
$host = $url['host'];
$port = $url['port'];
$password = $url['pass'] ?? null;
$cacheEngine = new RedisCache($host, $port, $password);
break;
}
}
$api = new \Sovit\TikTok\Api($options, $cacheEngine);