Laravel-Redis

思考并回答以下问题:

管道命令

当你需要在一次操作中发送多个命令到服务器的时候应该使用管道,pipeline方法接收一个参数:接收Redis实例的闭包。你可以将所有Redis命令发送到这个Redis实例,然后这些命令会在一次操作中被执行:

1
2
3
4
5
6
7
Redis::pipeline(function ($pipe) 
{
for ($i = 0; $i < 1000; $i++)
{
$pipe->set("key:$i", $i);
}
});

源码

Connections

Illuminate\Redis\Connections\Connection.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
<?php

namespace Illuminate\Redis\Connections;

use Closure;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Redis\Events\CommandExecuted;
use Illuminate\Redis\Limiters\ConcurrencyLimiterBuilder;
use Illuminate\Redis\Limiters\DurationLimiterBuilder;
use Illuminate\Support\Traits\Macroable;

abstract class Connection
{
use Macroable {
__call as macroCall;
}

/**
* The Redis client.
*
* @var \Redis
*/
protected $client;

/**
* The Redis connection name.
*
* @var string|null
*/
protected $name;

/**
* The event dispatcher instance.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected $events;

/**
* 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 = [])
{
$start = microtime(true);

$result = $this->client->{$method}(...$parameters);

$time = round((microtime(true) - $start) * 1000, 2);

if (isset($this->events)) {
$this->event(new CommandExecuted($method, $parameters, $time, $this));
}

return $result;
}

/**
* Fire the given event if possible.
*
* @param mixed $event
* @return void
*/
protected function event($event)
{
if (isset($this->events)) {
$this->events->dispatch($event);
}
}

/**
* Register a Redis command listener with the connection.
*
* @param \Closure $callback
* @return void
*/
public function listen(Closure $callback)
{
if (isset($this->events)) {
$this->events->listen(CommandExecuted::class, $callback);
}
}

/**
* Get the connection name.
*
* @return string|null
*/
public function getName()
{
return $this->name;
}

/**
* Set the connections name.
*
* @param string $name
* @return $this
*/
public function setName($name)
{
$this->name = $name;

return $this;
}

/**
* Get the event dispatcher used by the connection.
*
* @return \Illuminate\Contracts\Events\Dispatcher
*/
public function getEventDispatcher()
{
return $this->events;
}

/**
* Set the event dispatcher instance on the connection.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function setEventDispatcher(Dispatcher $events)
{
$this->events = $events;
}

/**
* Unset the event dispatcher instance on the connection.
*
* @return void
*/
public function unsetEventDispatcher()
{
$this->events = null;
}

/**
* Pass other method calls down to the underlying client.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}

return $this->command($method, $parameters);
}
}

Illuminate\Contracts\Redis\Connection.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php

namespace Illuminate\Contracts\Redis;

use Closure;

interface Connection
{
/**
* Subscribe to a set of given channels for messages.
*
* @param array|string $channels
* @param \Closure $callback
* @return void
*/
public function subscribe($channels, Closure $callback);

/**
* Subscribe to a set of given channels with wildcards.
*
* @param array|string $channels
* @param \Closure $callback
* @return void
*/
public function psubscribe($channels, Closure $callback);

/**
* Run a command against the Redis database.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function command($method, array $parameters = []);
}

Illuminate\Redis\Connections\PhpRedisConnection.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?php

namespace Illuminate\Redis\Connections;

use Closure;
use Illuminate\Contracts\Redis\Connection as ConnectionContract;
use Illuminate\Support\Str;
use Redis;
use RedisCluster;
use RedisException;

/**
* @mixin \Redis
*/
class PhpRedisConnection extends Connection implements ConnectionContract
{
/**
* The connection creation callback.
*
* @var callable
*/
protected $connector;

/**
* Create a new PhpRedis connection.
*
* @param \Redis $client
* @param callable|null $connector
* @return void
*/
public function __construct($client, callable $connector = null)
{
$this->client = $client;
$this->connector = $connector;
}

/**
* Returns the value of the given key.
*
* @param string $key
* @return string|null
*/
public function get($key)
{
$result = $this->command('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->command('mget', [$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->command('setnx', [$key, $value]);
}

/**
* Get the value of the given hash fields.
*
* @param string $key
* @param mixed $dictionary
* @return array
*/
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 mixed $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->command('hsetnx', [$hash, $key, $value]);
}

/**
* Removes the first count occurrences of the value element from the list.
*
* @param string $key
* @param int $count
* @param mixed $value
* @return int|false
*/
public function lrem($key, $count, $value)
{
return $this->command('lrem', [$key, $value, $count]);
}

/**
* Removes and returns the first element of the list stored at key.
*
* @param mixed $arguments
* @return array|null
*/
public function blpop(...$arguments)
{
$result = $this->command('blpop', $arguments);

return empty($result) ? null : $result;
}

/**
* Removes and returns the last element of the list stored at key.
*
* @param mixed $arguments
* @return array|null
*/
public function brpop(...$arguments)
{
$result = $this->command('brpop', $arguments);

return empty($result) ? null : $result;
}

/**
* 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 = 1)
{
return $this->command('spop', [$key, $count]);
}

/**
* Add one or more members to a sorted set or update its score if it already exists.
*
* @param string $key
* @param mixed $dictionary
* @return int
*/
public function zadd($key, ...$dictionary)
{
if (is_array(end($dictionary))) {
foreach (array_pop($dictionary) as $member => $score) {
$dictionary[] = $score;
$dictionary[] = $member;
}
}

$options = [];

foreach (array_slice($dictionary, 0, 3) as $i => $value) {
if (in_array($value, ['nx', 'xx', 'ch', 'incr', 'NX', 'XX', 'CH', 'INCR'], true)) {
$options[] = $value;

unset($dictionary[$i]);
}
}

return $this->command('zadd', array_merge([$key], [$options], array_values($dictionary)));
}

/**
* Return elements with score between $min and $max.
*
* @param string $key
* @param mixed $min
* @param mixed $max
* @param array $options
* @return array
*/
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 array
*/
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->command('zinterstore', [$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->command('zunionstore', [$output, $keys,
$options['weights'] ?? null,
$options['aggregate'] ?? 'sum',
]);
}

/**
* Execute commands in a pipeline.
*
* @param callable|null $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|null $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->command('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')
{
//
}

/**
* Flush the selected Redis database.
*
* @return void
*/
public function flushdb()
{
if (! $this->client instanceof RedisCluster) {
return $this->command('flushdb');
}

foreach ($this->client->_masters() as [$host, $port]) {
tap(new Redis)->connect($host, $port)->flushDb();
}
}

/**
* Execute a raw command.
*
* @param array $parameters
* @return mixed
*/
public function executeRaw(array $parameters)
{
return $this->command('rawCommand', $parameters);
}

/**
* Run a command against the Redis database.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function command($method, array $parameters = [])
{
try {
return parent::command($method, $parameters);
} catch (RedisException $e) {
if (Str::contains($e->getMessage(), 'went away')) {
$this->client = $this->connector ? call_user_func($this->connector) : $this->client;
}

throw $e;
}
}

/**
* 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)
{
return parent::__call(strtolower($method), $parameters);
}
}

Illuminate\Redis\Connections\PredisConnection.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php

namespace Illuminate\Redis\Connections;

use Closure;
use Illuminate\Contracts\Redis\Connection as ConnectionContract;
use Predis\Command\ServerFlushDatabase;
use Predis\Connection\Aggregate\ClusterInterface;

/**
* @mixin \Predis\Client
* @deprecated Predis is no longer maintained by its original author
*/
class PredisConnection extends Connection implements ConnectionContract
{
/**
* The Predis client.
*
* @var \Predis\Client
*/
protected $client;

/**
* 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);
}

/**
* Flush the selected Redis database.
*
* @return void
*/
public function flushdb()
{
if (! $this->client->getConnection() instanceof ClusterInterface) {
return $this->command('flushdb');
}

foreach ($this->getConnection() as $node) {
$node->executeCommand(new ServerFlushDatabase);
}
}
}

Connector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
<?php

namespace Illuminate\Redis\Connectors;

use Illuminate\Contracts\Redis\Connector;
use Illuminate\Redis\Connections\PhpRedisClusterConnection;
use Illuminate\Redis\Connections\PhpRedisConnection;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Redis as RedisFacade;
use LogicException;
use Redis;
use RedisCluster;

class PhpRedisConnector implements Connector
{
/**
* Create a new clustered PhpRedis connection.
*
* @param array $config
* @param array $options
* @return \Illuminate\Redis\Connections\PhpRedisConnection
*/
public function connect(array $config, array $options)
{
$connector = function () use ($config, $options) {
return $this->createClient(array_merge(
$config, $options, Arr::pull($config, 'options', [])
));
};

return new PhpRedisConnection($connector(), $connector);
}

/**
* 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'].'?'.Arr::query(Arr::only($server, [
'database', 'password', 'prefix', 'read_timeout',
]));
}

/**
* Create the Redis client instance.
*
* @param array $config
* @return \Redis
*
* @throws \LogicException
*/
protected function createClient(array $config)
{
return tap(new Redis, function ($client) use ($config) {
if ($client instanceof RedisFacade) {
throw new LogicException(
extension_loaded('redis')
? 'Please remove or rename the Redis facade alias in your "app" configuration file in order to avoid collision with the PHP Redis extension.'
: 'Please make sure the PHP Redis extension is installed and enabled.'
);
}

$this->establishConnection($client, $config);

if (! empty($config['password'])) {
$client->auth($config['password']);
}

if (isset($config['database'])) {
$client->select((int) $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']);
}

if (! empty($config['scan'])) {
$client->setOption(Redis::OPT_SCAN, $config['scan']);
}
});
}

/**
* Establish a connection with the Redis host.
*
* @param \Redis $client
* @param array $config
* @return void
*/
protected function establishConnection($client, array $config)
{
$persistent = $config['persistent'] ?? false;

$parameters = [
$config['host'],
$config['port'],
Arr::get($config, 'timeout', 0.0),
$persistent ? Arr::get($config, 'persistent_id', null) : null,
Arr::get($config, 'retry_interval', 0),
];

if (version_compare(phpversion('redis'), '3.1.3', '>=')) {
$parameters[] = Arr::get($config, 'read_timeout', 0.0);
}

$client->{($persistent ? 'pconnect' : 'connect')}(...$parameters);
}

/**
* Create a new redis cluster instance.
*
* @param array $servers
* @param array $options
* @return \RedisCluster
*/
protected function createRedisClusterInstance(array $servers, array $options)
{
$parameters = [
null,
array_values($servers),
$options['timeout'] ?? 0,
$options['read_timeout'] ?? 0,
isset($options['persistent']) && $options['persistent'],
];

if (version_compare(phpversion('redis'), '4.3.0', '>=')) {
$parameters[] = $options['password'] ?? null;
}

return tap(new RedisCluster(...$parameters), function ($client) use ($options) {
if (! empty($options['prefix'])) {
$client->setOption(RedisCluster::OPT_PREFIX, $options['prefix']);
}

if (! empty($options['scan'])) {
$client->setOption(RedisCluster::OPT_SCAN, $options['scan']);
}

if (! empty($options['failover'])) {
$client->setOption(RedisCluster::OPT_SLAVE_FAILOVER, $options['failover']);
}
});
}
}

RedisManager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php

namespace Illuminate\Redis;

use Closure;
use Illuminate\Contracts\Redis\Factory;
use Illuminate\Redis\Connections\Connection;
use Illuminate\Redis\Connectors\PhpRedisConnector;
use Illuminate\Redis\Connectors\PredisConnector;
use Illuminate\Support\ConfigurationUrlParser;
use InvalidArgumentException;


/**
* @mixin \Illuminate\Redis\Connections\Connection
*/
class RedisManager implements Factory
{
/**
* The application instance.
*
* @var \Illuminate\Contracts\Foundation\Application
*/
protected $app;

/**
* The name of the default driver.
*
* @var string
*/
protected $driver;

/**
* The registered custom driver creators.
*
* @var array
*/
protected $customCreators = [];

/**
* The Redis server configurations.
*
* @var array
*/
protected $config;

/**
* The Redis connections.
*
* @var mixed
*/
protected $connections;

/**
* Indicates whether event dispatcher is set on connections.
*
* @var bool
*/
protected $events = false;

/**
* Create a new Redis manager instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param string $driver
* @param array $config
* @return void
*/
public function __construct($app, $driver, array $config)
{
$this->app = $app;
$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->configure(
$this->resolve($name), $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->parseConnectionConfiguration($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)
{
return $this->connector()->connectToCluster(
array_map(function ($config) {
return $this->parseConnectionConfiguration($config);
}, $this->config['clusters'][$name]),
$this->config['clusters']['options'] ?? [],
$this->config['options'] ?? []
);
}

/**
* Configure the given connection to prepare it for commands.
*
* @param \Illuminate\Redis\Connections\Connection $connection
* @param string $name
* @return \Illuminate\Redis\Connections\Connection
*/
protected function configure(Connection $connection, $name)
{
$connection->setName($name);

if ($this->events && $this->app->bound('events')) {
$connection->setEventDispatcher($this->app->make('events'));
}

return $connection;
}

/**
* Get the connector instance for the current driver.
*
* @return \Illuminate\Contracts\Redis\Connector
*/
protected function connector()
{
$customCreator = $this->customCreators[$this->driver] ?? null;

if ($customCreator) {
return $customCreator();
}

switch ($this->driver) {
case 'predis':
return new PredisConnector;
case 'phpredis':
return new PhpRedisConnector;
}
}

/**
* Parse the Redis connection configuration.
*
* @param mixed $config
* @return array
*/
protected function parseConnectionConfiguration($config)
{
$parsed = (new ConfigurationUrlParser)->parseConfiguration($config);

return array_filter($parsed, function ($key) {
return ! in_array($key, ['driver', 'username'], true);
}, ARRAY_FILTER_USE_KEY);
}

/**
* Return all of the created connections.
*
* @return array
*/
public function connections()
{
return $this->connections;
}

/**
* Enable the firing of Redis command events.
*
* @return void
*/
public function enableEvents()
{
$this->events = true;
}

/**
* Disable the firing of Redis command events.
*
* @return void
*/
public function disableEvents()
{
$this->events = false;
}

/**
* Set the default driver.
*
* @param string $driver
* @return void
*/
public function setDriver($driver)
{
$this->driver = $driver;
}

/**
* Register a custom driver creator Closure.
*
* @param string $driver
* @param \Closure $callback
* @return $this
*/
public function extend($driver, Closure $callback)
{
$this->customCreators[$driver] = $callback->bindTo($this, $this);

return $this;
}

/**
* 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);
}
}

RedisServiceProvider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php

namespace Illuminate\Redis;

use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\Arr;
use Illuminate\Support\ServiceProvider;

class RedisServiceProvider extends ServiceProvider implements DeferrableProvider
{
/**
* 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($app, Arr::pull($config, 'client', 'phpredis'), $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'];
}
}
0%