You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
1.7 KiB
PHP
80 lines
1.7 KiB
PHP
<?php
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
use Predis\Client;
|
|
|
|
class RedisClient
|
|
{
|
|
private static $sharedClient;
|
|
|
|
public $client;
|
|
|
|
public function __construct()
|
|
{
|
|
if (self::$sharedClient === null) {
|
|
$config = [
|
|
'scheme' => Config::get('redis_scheme'),
|
|
'password' => Config::get('redis_password'),
|
|
'host' => Config::get('redis_host'),
|
|
'port' => Config::get('redis_port'),
|
|
'database' => Config::get('redis_database'),
|
|
];
|
|
self::$sharedClient = new Client($config);
|
|
}
|
|
|
|
$this->client = self::$sharedClient;
|
|
}
|
|
|
|
public function getClient()
|
|
{
|
|
return $this->client;
|
|
}
|
|
|
|
/**
|
|
* Release request-local Redis state for long-running commands and tests.
|
|
*/
|
|
public static function resetSharedClient()
|
|
{
|
|
self::$sharedClient = null;
|
|
}
|
|
|
|
public function get($key, $minutes = null, $callback = null)
|
|
{
|
|
$value = $this->client->get($key);
|
|
if ($value === null && $callback !== null) {
|
|
$value = $callback();
|
|
if ($minutes !== null) {
|
|
$this->setex($key, $minutes * 60, $value); // 缓存数据
|
|
} else {
|
|
$this->set($key, $value);
|
|
}
|
|
}
|
|
return $value;
|
|
}
|
|
|
|
public function set($key, $value)
|
|
{
|
|
$this->client->set($key, $value);
|
|
}
|
|
|
|
public function setex($key, $time, $value)
|
|
{
|
|
$this->client->setex($key, $time, $value);
|
|
}
|
|
|
|
public function del($key)
|
|
{
|
|
$this->client->del($key);
|
|
}
|
|
|
|
public function deleteMultiple(array $keys)
|
|
{
|
|
foreach ($keys as $key) {
|
|
$this->client->del($key);
|
|
}
|
|
}
|
|
|
|
}
|