Include Vendor

This commit is contained in:
Mathieu Lagace
2018-06-27 20:31:54 -04:00
parent d0807a7cf5
commit 5fa3c85b97
6624 changed files with 728653 additions and 1 deletions

View File

@@ -0,0 +1,110 @@
<?php
namespace Illuminate\Redis\Connections;
use Closure;
use Illuminate\Redis\Limiters\DurationLimiterBuilder;
use Illuminate\Redis\Limiters\ConcurrencyLimiterBuilder;
/**
* @mixin \Predis\Client
*/
abstract class Connection
{
/**
* The Predis client.
*
* @var \Predis\Client
*/
protected $client;
/**
* Subscribe to a set of given channels for messages.
*
* @param array|string $channels
* @param \Closure $callback
* @param string $method
* @return void
*/
abstract public function createSubscription($channels, Closure $callback, $method = 'subscribe');
/**
* Funnel a callback for a maximum number of simultaneous executions.
*
* @param string $name
* @return \Illuminate\Redis\Limiters\ConcurrencyLimiterBuilder
*/
public function funnel($name)
{
return new ConcurrencyLimiterBuilder($this, $name);
}
/**
* Throttle a callback for a maximum number of executions over a given duration.
*
* @param string $name
* @return \Illuminate\Redis\Limiters\DurationLimiterBuilder
*/
public function throttle($name)
{
return new DurationLimiterBuilder($this, $name);
}
/**
* Get the underlying Redis client.
*
* @return mixed
*/
public function client()
{
return $this->client;
}
/**
* Subscribe to a set of given channels for messages.
*
* @param array|string $channels
* @param \Closure $callback
* @return void
*/
public function subscribe($channels, Closure $callback)
{
return $this->createSubscription($channels, $callback, __FUNCTION__);
}
/**
* Subscribe to a set of given channels with wildcards.
*
* @param array|string $channels
* @param \Closure $callback
* @return void
*/
public function psubscribe($channels, Closure $callback)
{
return $this->createSubscription($channels, $callback, __FUNCTION__);
}
/**
* Run a command against the Redis database.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function command($method, array $parameters = [])
{
return $this->client->{$method}(...$parameters);
}
/**
* Pass other method calls down to the underlying client.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->command($method, $parameters);
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Illuminate\Redis\Connections;
class PhpRedisClusterConnection extends PhpRedisConnection
{
//
}

View File

@@ -0,0 +1,412 @@
<?php
namespace Illuminate\Redis\Connections;
use Redis;
use Closure;
use Illuminate\Contracts\Redis\Connection as ConnectionContract;
/**
* @mixin \Redis
*/
class PhpRedisConnection extends Connection implements ConnectionContract
{
/**
* Create a new PhpRedis connection.
*
* @param \Redis $client
* @return void
*/
public function __construct($client)
{
$this->client = $client;
}
/**
* Returns the value of the given key.
*
* @param string $key
* @return string|null
*/
public function get($key)
{
$result = $this->client->get($key);
return $result !== false ? $result : null;
}
/**
* Get the values of all the given keys.
*
* @param array $keys
* @return array
*/
public function mget(array $keys)
{
return array_map(function ($value) {
return $value !== false ? $value : null;
}, $this->client->mget($keys));
}
/**
* Determine if the given keys exist.
*
* @param dynamic $keys
* @return int
*/
public function exists(...$keys)
{
$keys = collect($keys)->map(function ($key) {
return $this->applyPrefix($key);
})->all();
return $this->executeRaw(array_merge(['exists'], $keys));
}
/**
* Set the string value in argument as value of the key.
*
* @param string $key
* @param mixed $value
* @param string|null $expireResolution
* @param int|null $expireTTL
* @param string|null $flag
* @return bool
*/
public function set($key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
{
return $this->command('set', [
$key,
$value,
$expireResolution ? [$flag, $expireResolution => $expireTTL] : null,
]);
}
/**
* Set the given key if it doesn't exist.
*
* @param string $key
* @param string $value
* @return int
*/
public function setnx($key, $value)
{
return (int) $this->client->setnx($key, $value);
}
/**
* Get the value of the given hash fields.
*
* @param string $key
* @param dynamic $dictionary
* @return int
*/
public function hmget($key, ...$dictionary)
{
if (count($dictionary) == 1) {
$dictionary = $dictionary[0];
}
return array_values($this->command('hmget', [$key, $dictionary]));
}
/**
* Set the given hash fields to their respective values.
*
* @param string $key
* @param dynamic $dictionary
* @return int
*/
public function hmset($key, ...$dictionary)
{
if (count($dictionary) == 1) {
$dictionary = $dictionary[0];
} else {
$input = collect($dictionary);
$dictionary = $input->nth(2)->combine($input->nth(2, 1))->toArray();
}
return $this->command('hmset', [$key, $dictionary]);
}
/**
* Set the given hash field if it doesn't exist.
*
* @param string $hash
* @param string $key
* @param string $value
* @return int
*/
public function hsetnx($hash, $key, $value)
{
return (int) $this->client->hsetnx($hash, $key, $value);
}
/**
* Removes the first count occurrences of the value element from the list.
*
* @param string $key
* @param int $count
* @param $value $value
* @return int|false
*/
public function lrem($key, $count, $value)
{
return $this->command('lrem', [$key, $value, $count]);
}
/**
* Removes and returns a random element from the set value at key.
*
* @param string $key
* @param int|null $count
* @return mixed|false
*/
public function spop($key, $count = null)
{
return $this->command('spop', [$key]);
}
/**
* Add one or more members to a sorted set or update its score if it already exists.
*
* @param string $key
* @param dynamic $dictionary
* @return int
*/
public function zadd($key, ...$dictionary)
{
if (is_array(end($dictionary))) {
foreach (array_pop($dictionary) as $member => $score) {
$dictionary[] = $score;
$dictionary[] = $member;
}
}
$key = $this->applyPrefix($key);
return $this->executeRaw(array_merge(['zadd', $key], $dictionary));
}
/**
* Return elements with score between $min and $max.
*
* @param string $key
* @param mixed $min
* @param mixed $max
* @param array $options
* @return int
*/
public function zrangebyscore($key, $min, $max, $options = [])
{
if (isset($options['limit'])) {
$options['limit'] = [
$options['limit']['offset'],
$options['limit']['count'],
];
}
return $this->command('zRangeByScore', [$key, $min, $max, $options]);
}
/**
* Return elements with score between $min and $max.
*
* @param string $key
* @param mixed $min
* @param mixed $max
* @param array $options
* @return int
*/
public function zrevrangebyscore($key, $min, $max, $options = [])
{
if (isset($options['limit'])) {
$options['limit'] = [
$options['limit']['offset'],
$options['limit']['count'],
];
}
return $this->command('zRevRangeByScore', [$key, $min, $max, $options]);
}
/**
* Find the intersection between sets and store in a new set.
*
* @param string $output
* @param array $keys
* @param array $options
* @return int
*/
public function zinterstore($output, $keys, $options = [])
{
return $this->zInter($output, $keys,
$options['weights'] ?? null,
$options['aggregate'] ?? 'sum'
);
}
/**
* Find the union between sets and store in a new set.
*
* @param string $output
* @param array $keys
* @param array $options
* @return int
*/
public function zunionstore($output, $keys, $options = [])
{
return $this->zUnion($output, $keys,
$options['weights'] ?? null,
$options['aggregate'] ?? 'sum'
);
}
/**
* Execute commands in a pipeline.
*
* @param callable $callback
* @return \Redis|array
*/
public function pipeline(callable $callback = null)
{
$pipeline = $this->client()->pipeline();
return is_null($callback)
? $pipeline
: tap($pipeline, $callback)->exec();
}
/**
* Execute commands in a transaction.
*
* @param callable $callback
* @return \Redis|array
*/
public function transaction(callable $callback = null)
{
$transaction = $this->client()->multi();
return is_null($callback)
? $transaction
: tap($transaction, $callback)->exec();
}
/**
* Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself.
*
* @param string $script
* @param int $numkeys
* @param mixed $arguments
* @return mixed
*/
public function evalsha($script, $numkeys, ...$arguments)
{
return $this->command('evalsha', [
$this->script('load', $script), $arguments, $numkeys,
]);
}
/**
* Evaluate a script and return its result.
*
* @param string $script
* @param int $numberOfKeys
* @param dynamic $arguments
* @return mixed
*/
public function eval($script, $numberOfKeys, ...$arguments)
{
return $this->client->eval($script, $arguments, $numberOfKeys);
}
/**
* Subscribe to a set of given channels for messages.
*
* @param array|string $channels
* @param \Closure $callback
* @return void
*/
public function subscribe($channels, Closure $callback)
{
$this->client->subscribe((array) $channels, function ($redis, $channel, $message) use ($callback) {
$callback($message, $channel);
});
}
/**
* Subscribe to a set of given channels with wildcards.
*
* @param array|string $channels
* @param \Closure $callback
* @return void
*/
public function psubscribe($channels, Closure $callback)
{
$this->client->psubscribe((array) $channels, function ($redis, $pattern, $channel, $message) use ($callback) {
$callback($message, $channel);
});
}
/**
* Subscribe to a set of given channels for messages.
*
* @param array|string $channels
* @param \Closure $callback
* @param string $method
* @return void
*/
public function createSubscription($channels, Closure $callback, $method = 'subscribe')
{
//
}
/**
* Execute a raw command.
*
* @param array $parameters
* @return mixed
*/
public function executeRaw(array $parameters)
{
return $this->command('rawCommand', $parameters);
}
/**
* Disconnects from the Redis instance.
*
* @return void
*/
public function disconnect()
{
$this->client->close();
}
/**
* Apply prefix to the given key if necessary.
*
* @param string $key
* @return string
*/
private function applyPrefix($key)
{
$prefix = (string) $this->client->getOption(Redis::OPT_PREFIX);
return $prefix.$key;
}
/**
* Pass other method calls down to the underlying client.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
$method = strtolower($method);
return parent::__call($method, $parameters);
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Illuminate\Redis\Connections;
class PredisClusterConnection extends PredisConnection
{
//
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Illuminate\Redis\Connections;
use Closure;
use Illuminate\Contracts\Redis\Connection as ConnectionContract;
/**
* @mixin \Predis\Client
*/
class PredisConnection extends Connection implements ConnectionContract
{
/**
* Create a new Predis connection.
*
* @param \Predis\Client $client
* @return void
*/
public function __construct($client)
{
$this->client = $client;
}
/**
* Subscribe to a set of given channels for messages.
*
* @param array|string $channels
* @param \Closure $callback
* @param string $method
* @return void
*/
public function createSubscription($channels, Closure $callback, $method = 'subscribe')
{
$loop = $this->pubSubLoop();
call_user_func_array([$loop, $method], (array) $channels);
foreach ($loop as $message) {
if ($message->kind === 'message' || $message->kind === 'pmessage') {
call_user_func($callback, $message->payload, $message->channel);
}
}
unset($loop);
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace Illuminate\Redis\Connectors;
use Redis;
use RedisCluster;
use Illuminate\Support\Arr;
use Illuminate\Redis\Connections\PhpRedisConnection;
use Illuminate\Redis\Connections\PhpRedisClusterConnection;
class PhpRedisConnector
{
/**
* Create a new clustered PhpRedis connection.
*
* @param array $config
* @param array $options
* @return \Illuminate\Redis\Connections\PhpRedisConnection
*/
public function connect(array $config, array $options)
{
return new PhpRedisConnection($this->createClient(array_merge(
$config, $options, Arr::pull($config, 'options', [])
)));
}
/**
* Create a new clustered PhpRedis connection.
*
* @param array $config
* @param array $clusterOptions
* @param array $options
* @return \Illuminate\Redis\Connections\PhpRedisClusterConnection
*/
public function connectToCluster(array $config, array $clusterOptions, array $options)
{
$options = array_merge($options, $clusterOptions, Arr::pull($config, 'options', []));
return new PhpRedisClusterConnection($this->createRedisClusterInstance(
array_map([$this, 'buildClusterConnectionString'], $config), $options
));
}
/**
* Build a single cluster seed string from array.
*
* @param array $server
* @return string
*/
protected function buildClusterConnectionString(array $server)
{
return $server['host'].':'.$server['port'].'?'.http_build_query(Arr::only($server, [
'database', 'password', 'prefix', 'read_timeout',
]));
}
/**
* Create the Redis client instance.
*
* @param array $config
* @return \Redis
*/
protected function createClient(array $config)
{
return tap(new Redis, function ($client) use ($config) {
$this->establishConnection($client, $config);
if (! empty($config['password'])) {
$client->auth($config['password']);
}
if (! empty($config['database'])) {
$client->select($config['database']);
}
if (! empty($config['prefix'])) {
$client->setOption(Redis::OPT_PREFIX, $config['prefix']);
}
if (! empty($config['read_timeout'])) {
$client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']);
}
});
}
/**
* Establish a connection with the Redis host.
*
* @param \Redis $client
* @param array $config
* @return void
*/
protected function establishConnection($client, array $config)
{
$client->{($config['persistent'] ?? false) === true ? 'pconnect' : 'connect'}(
$config['host'], $config['port'], Arr::get($config, 'timeout', 0)
);
}
/**
* Create a new redis cluster instance.
*
* @param array $servers
* @param array $options
* @return \RedisCluster
*/
protected function createRedisClusterInstance(array $servers, array $options)
{
return new RedisCluster(
null,
array_values($servers),
$options['timeout'] ?? 0,
$options['read_timeout'] ?? 0,
isset($options['persistent']) && $options['persistent']
);
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Illuminate\Redis\Connectors;
use Predis\Client;
use Illuminate\Support\Arr;
use Illuminate\Redis\Connections\PredisConnection;
use Illuminate\Redis\Connections\PredisClusterConnection;
class PredisConnector
{
/**
* Create a new clustered Predis connection.
*
* @param array $config
* @param array $options
* @return \Illuminate\Redis\Connections\PredisConnection
*/
public function connect(array $config, array $options)
{
$formattedOptions = array_merge(
['timeout' => 10.0], $options, Arr::pull($config, 'options', [])
);
return new PredisConnection(new Client($config, $formattedOptions));
}
/**
* Create a new clustered Predis connection.
*
* @param array $config
* @param array $clusterOptions
* @param array $options
* @return \Illuminate\Redis\Connections\PredisClusterConnection
*/
public function connectToCluster(array $config, array $clusterOptions, array $options)
{
$clusterSpecificOptions = Arr::pull($config, 'options', []);
return new PredisClusterConnection(new Client(array_values($config), array_merge(
$options, $clusterOptions, $clusterSpecificOptions
)));
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Illuminate\Redis\Limiters;
use Illuminate\Contracts\Redis\LimiterTimeoutException;
class ConcurrencyLimiter
{
/**
* The Redis factory implementation.
*
* @var \Illuminate\Redis\Connections\Connection
*/
protected $redis;
/**
* The name of the limiter.
*
* @var string
*/
protected $name;
/**
* The allowed number of concurrent tasks.
*
* @var int
*/
protected $maxLocks;
/**
* The number of seconds a slot should be maintained.
*
* @var int
*/
protected $releaseAfter;
/**
* Create a new concurrency limiter instance.
*
* @param \Illuminate\Redis\Connections\Connection $redis
* @param string $name
* @param int $maxLocks
* @param int $releaseAfter
* @return void
*/
public function __construct($redis, $name, $maxLocks, $releaseAfter)
{
$this->name = $name;
$this->redis = $redis;
$this->maxLocks = $maxLocks;
$this->releaseAfter = $releaseAfter;
}
/**
* Attempt to acquire the lock for the given number of seconds.
*
* @param int $timeout
* @param callable|null $callback
* @return bool
* @throws \Illuminate\Contracts\Redis\LimiterTimeoutException
*/
public function block($timeout, $callback = null)
{
$starting = time();
while (! $slot = $this->acquire()) {
if (time() - $timeout >= $starting) {
throw new LimiterTimeoutException;
}
usleep(250 * 1000);
}
if (is_callable($callback)) {
return tap($callback(), function () use ($slot) {
$this->release($slot);
});
}
return true;
}
/**
* Attempt to acquire the lock.
*
* @return mixed
*/
protected function acquire()
{
$slots = array_map(function ($i) {
return $this->name.$i;
}, range(1, $this->maxLocks));
return $this->redis->eval($this->luaScript(), count($slots),
...array_merge($slots, [$this->name, $this->releaseAfter])
);
}
/**
* Get the Lua script for acquiring a lock.
*
* KEYS - The keys that represent available slots
* ARGV[1] - The limiter name
* ARGV[2] - The number of seconds the slot should be reserved
*
* @return string
*/
protected function luaScript()
{
return <<<'LUA'
for index, value in pairs(redis.call('mget', unpack(KEYS))) do
if not value then
redis.call('set', ARGV[1]..index, "1", "EX", ARGV[2])
return ARGV[1]..index
end
end
LUA;
}
/**
* Release the lock.
*
* @param string $key
* @return void
*/
protected function release($key)
{
$this->redis->del($key);
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace Illuminate\Redis\Limiters;
use Illuminate\Support\InteractsWithTime;
use Illuminate\Contracts\Redis\LimiterTimeoutException;
class ConcurrencyLimiterBuilder
{
use InteractsWithTime;
/**
* The Redis connection.
*
* @var \Illuminate\Redis\Connections\Connection
*/
public $connection;
/**
* The name of the lock.
*
* @var string
*/
public $name;
/**
* The maximum number of entities that can hold the lock at the same time.
*
* @var int
*/
public $maxLocks;
/**
* The number of seconds to maintain the lock until it is automatically released.
*
* @var int
*/
public $releaseAfter = 60;
/**
* The amount of time to block until a lock is available.
*
* @var int
*/
public $timeout = 3;
/**
* Create a new builder instance.
*
* @param \Illuminate\Redis\Connections\Connection $connection
* @param string $name
* @return void
*/
public function __construct($connection, $name)
{
$this->name = $name;
$this->connection = $connection;
}
/**
* Set the maximum number of locks that can obtained per time window.
*
* @param int $maxLocks
* @return $this
*/
public function limit($maxLocks)
{
$this->maxLocks = $maxLocks;
return $this;
}
/**
* Set the number of seconds until the lock will be released.
*
* @param int $releaseAfter
* @return $this
*/
public function releaseAfter($releaseAfter)
{
$this->releaseAfter = $this->secondsUntil($releaseAfter);
return $this;
}
/**
* Set the amount of time to block until a lock is available.
*
* @param int $timeout
* @return $this
*/
public function block($timeout)
{
$this->timeout = $timeout;
return $this;
}
/**
* Execute the given callback if a lock is obtained, otherwise call the failure callback.
*
* @param callable $callback
* @param callable|null $failure
* @return mixed
*
* @throws \Illuminate\Contracts\Redis\LimiterTimeoutException
*/
public function then(callable $callback, callable $failure = null)
{
try {
return (new ConcurrencyLimiter(
$this->connection, $this->name, $this->maxLocks, $this->releaseAfter
))->block($this->timeout, $callback);
} catch (LimiterTimeoutException $e) {
if ($failure) {
return $failure($e);
}
throw $e;
}
}
}

View File

@@ -0,0 +1,147 @@
<?php
namespace Illuminate\Redis\Limiters;
use Illuminate\Contracts\Redis\LimiterTimeoutException;
class DurationLimiter
{
/**
* The Redis factory implementation.
*
* @var \Illuminate\Redis\Connections\Connection
*/
private $redis;
/**
* The unique name of the lock.
*
* @var string
*/
private $name;
/**
* The allowed number of concurrent tasks.
*
* @var int
*/
private $maxLocks;
/**
* The number of seconds a slot should be maintained.
*
* @var int
*/
private $decay;
/**
* The timestamp of the end of the current duration.
*
* @var int
*/
public $decaysAt;
/**
* The number of remaining slots.
*
* @var int
*/
public $remaining;
/**
* Create a new duration limiter instance.
*
* @param \Illuminate\Redis\Connections\Connection $redis
* @param string $name
* @param int $maxLocks
* @param int $decay
* @return void
*/
public function __construct($redis, $name, $maxLocks, $decay)
{
$this->name = $name;
$this->decay = $decay;
$this->redis = $redis;
$this->maxLocks = $maxLocks;
}
/**
* Attempt to acquire the lock for the given number of seconds.
*
* @param int $timeout
* @param callable|null $callback
* @return bool
* @throws \Illuminate\Contracts\Redis\LimiterTimeoutException
*/
public function block($timeout, $callback = null)
{
$starting = time();
while (! $this->acquire()) {
if (time() - $timeout >= $starting) {
throw new LimiterTimeoutException;
}
usleep(750 * 1000);
}
if (is_callable($callback)) {
$callback();
}
return true;
}
/**
* Attempt to acquire the lock.
*
* @return bool
*/
public function acquire()
{
$results = $this->redis->eval($this->luaScript(), 1,
$this->name, microtime(true), time(), $this->decay, $this->maxLocks
);
$this->decaysAt = $results[1];
$this->remaining = max(0, $results[2]);
return (bool) $results[0];
}
/**
* Get the Lua script for acquiring a lock.
*
* KEYS[1] - The limiter name
* ARGV[1] - Current time in microseconds
* ARGV[2] - Current time in seconds
* ARGV[3] - Duration of the bucket
* ARGV[4] - Allowed number of tasks
*
* @return string
*/
protected function luaScript()
{
return <<<'LUA'
local function reset()
redis.call('HMSET', KEYS[1], 'start', ARGV[2], 'end', ARGV[2] + ARGV[3], 'count', 1)
return redis.call('EXPIRE', KEYS[1], ARGV[3] * 2)
end
if redis.call('EXISTS', KEYS[1]) == 0 then
return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1}
end
if ARGV[1] >= redis.call('HGET', KEYS[1], 'start') and ARGV[1] <= redis.call('HGET', KEYS[1], 'end') then
return {
tonumber(redis.call('HINCRBY', KEYS[1], 'count', 1)) <= tonumber(ARGV[4]),
redis.call('HGET', KEYS[1], 'end'),
ARGV[4] - redis.call('HGET', KEYS[1], 'count')
}
end
return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1}
LUA;
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace Illuminate\Redis\Limiters;
use Illuminate\Support\InteractsWithTime;
use Illuminate\Contracts\Redis\LimiterTimeoutException;
class DurationLimiterBuilder
{
use InteractsWithTime;
/**
* The Redis connection.
*
* @var \Illuminate\Redis\Connections\Connection
*/
public $connection;
/**
* The name of the lock.
*
* @var string
*/
public $name;
/**
* The maximum number of locks that can obtained per time window.
*
* @var int
*/
public $maxLocks;
/**
* The amount of time the lock window is maintained.
*
* @var int
*/
public $decay;
/**
* The amount of time to block until a lock is available.
*
* @var int
*/
public $timeout = 3;
/**
* Create a new builder instance.
*
* @param \Illuminate\Redis\Connections\Connection $connection
* @param string $name
* @return void
*/
public function __construct($connection, $name)
{
$this->name = $name;
$this->connection = $connection;
}
/**
* Set the maximum number of locks that can obtained per time window.
*
* @param int $maxLocks
* @return $this
*/
public function allow($maxLocks)
{
$this->maxLocks = $maxLocks;
return $this;
}
/**
* Set the amount of time the lock window is maintained.
*
* @param int $decay
* @return $this
*/
public function every($decay)
{
$this->decay = $this->secondsUntil($decay);
return $this;
}
/**
* Set the amount of time to block until a lock is available.
*
* @param int $timeout
* @return $this
*/
public function block($timeout)
{
$this->timeout = $timeout;
return $this;
}
/**
* Execute the given callback if a lock is obtained, otherwise call the failure callback.
*
* @param callable $callback
* @param callable|null $failure
* @return mixed
*
* @throws \Illuminate\Contracts\Redis\LimiterTimeoutException
*/
public function then(callable $callback, callable $failure = null)
{
try {
return (new DurationLimiter(
$this->connection, $this->name, $this->maxLocks, $this->decay
))->block($this->timeout, $callback);
} catch (LimiterTimeoutException $e) {
if ($failure) {
return $failure($e);
}
throw $e;
}
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace Illuminate\Redis;
use InvalidArgumentException;
use Illuminate\Contracts\Redis\Factory;
/**
* @mixin \Illuminate\Redis\Connections\Connection
*/
class RedisManager implements Factory
{
/**
* The name of the default driver.
*
* @var string
*/
protected $driver;
/**
* The Redis server configurations.
*
* @var array
*/
protected $config;
/**
* The Redis connections.
*
* @var mixed
*/
protected $connections;
/**
* Create a new Redis manager instance.
*
* @param string $driver
* @param array $config
* @return void
*/
public function __construct($driver, array $config)
{
$this->driver = $driver;
$this->config = $config;
}
/**
* Get a Redis connection by name.
*
* @param string|null $name
* @return \Illuminate\Redis\Connections\Connection
*/
public function connection($name = null)
{
$name = $name ?: 'default';
if (isset($this->connections[$name])) {
return $this->connections[$name];
}
return $this->connections[$name] = $this->resolve($name);
}
/**
* Resolve the given connection by name.
*
* @param string|null $name
* @return \Illuminate\Redis\Connections\Connection
*
* @throws \InvalidArgumentException
*/
public function resolve($name = null)
{
$name = $name ?: 'default';
$options = $this->config['options'] ?? [];
if (isset($this->config[$name])) {
return $this->connector()->connect($this->config[$name], $options);
}
if (isset($this->config['clusters'][$name])) {
return $this->resolveCluster($name);
}
throw new InvalidArgumentException("Redis connection [{$name}] not configured.");
}
/**
* Resolve the given cluster connection by name.
*
* @param string $name
* @return \Illuminate\Redis\Connections\Connection
*/
protected function resolveCluster($name)
{
$clusterOptions = $this->config['clusters']['options'] ?? [];
return $this->connector()->connectToCluster(
$this->config['clusters'][$name], $clusterOptions, $this->config['options'] ?? []
);
}
/**
* Get the connector instance for the current driver.
*
* @return \Illuminate\Redis\Connectors\PhpRedisConnector|\Illuminate\Redis\Connectors\PredisConnector
*/
protected function connector()
{
switch ($this->driver) {
case 'predis':
return new Connectors\PredisConnector;
case 'phpredis':
return new Connectors\PhpRedisConnector;
}
}
/**
* Return all of the created connections.
*
* @return array
*/
public function connections()
{
return $this->connections;
}
/**
* Pass methods onto the default Redis connection.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->connection()->{$method}(...$parameters);
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Illuminate\Redis;
use Illuminate\Support\Arr;
use Illuminate\Support\ServiceProvider;
class RedisServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('redis', function ($app) {
$config = $app->make('config')->get('database.redis');
return new RedisManager(Arr::pull($config, 'client', 'predis'), $config);
});
$this->app->bind('redis.connection', function ($app) {
return $app['redis']->connection();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['redis', 'redis.connection'];
}
}

View File

@@ -0,0 +1,36 @@
{
"name": "illuminate/redis",
"description": "The Illuminate Redis package.",
"license": "MIT",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"require": {
"php": "^7.1.3",
"illuminate/contracts": "5.6.*",
"illuminate/support": "5.6.*",
"predis/predis": "~1.0"
},
"autoload": {
"psr-4": {
"Illuminate\\Redis\\": ""
}
},
"extra": {
"branch-alias": {
"dev-master": "5.6-dev"
}
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev"
}