Debian Codegraph @

vendor/clue/redis-react/README.md

raw
1 # clue/reactphp-redis
2
3 [![CI status](https://github.com/clue/reactphp-redis/actions/workflows/ci.yml/badge.svg)](https://github.com/clue/reactphp-redis/actions)
4 [![installs on Packagist](https://img.shields.io/packagist/dt/clue/redis-react?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/clue/redis-react)
5
6 Async [Redis](https://redis.io/) client implementation, built on top of [ReactPHP](https://reactphp.org/).
7
8 [Redis](https://redis.io/) is an open source, advanced, in-memory key-value database.
9 It offers a set of simple, atomic operations in order to work with its primitive data types.
10 Its lightweight design and fast operation makes it an ideal candidate for modern application stacks.
11 This library provides you a simple API to work with your Redis database from within PHP.
12 It enables you to set and query its data or use its PubSub topics to react to incoming events.
13
14 * **Async execution of Commands** -
15 Send any number of commands to Redis in parallel (automatic pipeline) and
16 process their responses as soon as results come in.
17 The Promise-based design provides a *sane* interface to working with async responses.
18 * **Event-driven core** -
19 Register your event handler callbacks to react to incoming events, such as an incoming PubSub message event.
20 * **Lightweight, SOLID design** -
21 Provides a thin abstraction that is [*just good enough*](https://en.wikipedia.org/wiki/Principle_of_good_enough)
22 and does not get in your way.
23 Future or custom commands and events require no changes to be supported.
24 * **Good test coverage** -
25 Comes with an automated tests suite and is regularly tested against versions as old as Redis v2.6 and newer.
26
27 **Table of Contents**
28
29 * [Support us](#support-us)
30 * [Quickstart example](#quickstart-example)
31 * [Usage](#usage)
32 * [Commands](#commands)
33 * [Promises](#promises)
34 * [PubSub](#pubsub)
35 * [API](#api)
36 * [Factory](#factory)
37 * [createClient()](#createclient)
38 * [createLazyClient()](#createlazyclient)
39 * [Client](#client)
40 * [__call()](#__call)
41 * [end()](#end)
42 * [close()](#close)
43 * [error event](#error-event)
44 * [close event](#close-event)
45 * [Install](#install)
46 * [Tests](#tests)
47 * [License](#license)
48
49 ## Support us
50
51 We invest a lot of time developing, maintaining and updating our awesome
52 open-source projects. You can help us sustain this high-quality of our work by
53 [becoming a sponsor on GitHub](https://github.com/sponsors/clue). Sponsors get
54 numerous benefits in return, see our [sponsoring page](https://github.com/sponsors/clue)
55 for details.
56
57 Let's take these projects to the next level together! 🚀
58
59 ## Quickstart example
60
61 Once [installed](#install), you can use the following code to connect to your
62 local Redis server and send some requests:
63
64 ```php
65 <?php
66
67 require __DIR__ . '/vendor/autoload.php';
68
69 $factory = new Clue\React\Redis\Factory();
70 $redis = $factory->createLazyClient('localhost:6379');
71
72 $redis->set('greeting', 'Hello world');
73 $redis->append('greeting', '!');
74
75 $redis->get('greeting')->then(function ($greeting) {
76 // Hello world!
77 echo $greeting . PHP_EOL;
78 });
79
80 $redis->incr('invocation')->then(function ($n) {
81 echo 'This is invocation #' . $n . PHP_EOL;
82 });
83
84 // end connection once all pending requests have been resolved
85 $redis->end();
86 ```
87
88 See also the [examples](examples).
89
90 ## Usage
91
92 ### Commands
93
94 Most importantly, this project provides a [`Client`](#client) instance that
95 can be used to invoke all [Redis commands](https://redis.io/commands) (such as `GET`, `SET`, etc.).
96
97 ```php
98 $redis->get($key);
99 $redis->set($key, $value);
100 $redis->exists($key);
101 $redis->expire($key, $seconds);
102 $redis->mget($key1, $key2, $key3);
103
104 $redis->multi();
105 $redis->exec();
106
107 $redis->publish($channel, $payload);
108 $redis->subscribe($channel);
109
110 $redis->ping();
111 $redis->select($database);
112
113 // many more…
114 ```
115
116 Each method call matches the respective [Redis command](https://redis.io/commands).
117 For example, the `$redis->get()` method will invoke the [`GET` command](https://redis.io/commands/get).
118
119 All [Redis commands](https://redis.io/commands) are automatically available as
120 public methods via the magic [`__call()` method](#__call).
121 Listing all available commands is out of scope here, please refer to the
122 [Redis command reference](https://redis.io/commands).
123
124 Any arguments passed to the method call will be forwarded as command arguments.
125 For example, the `$redis->set('name', 'Alice')` call will perform the equivalent of a
126 `SET name Alice` command. It's safe to pass integer arguments where applicable (for
127 example `$redis->expire($key, 60)`), but internally Redis requires all arguments to
128 always be coerced to string values.
129
130 Each of these commands supports async operation and returns a [Promise](#promises)
131 that eventually *fulfills* with its *results* on success or *rejects* with an
132 `Exception` on error. See also the following section about [promises](#promises)
133 for more details.
134
135 ### Promises
136
137 Sending commands is async (non-blocking), so you can actually send multiple
138 commands in parallel.
139 Redis will respond to each command request with a response message, pending
140 commands will be pipelined automatically.
141
142 Sending commands uses a [Promise](https://github.com/reactphp/promise)-based
143 interface that makes it easy to react to when a command is completed
144 (i.e. either successfully fulfilled or rejected with an error):
145
146 ```php
147 $redis->get($key)->then(function (?string $value) {
148 var_dump($value);
149 }, function (Exception $e) {
150 echo 'Error: ' . $e->getMessage() . PHP_EOL;
151 });
152 ```
153
154 ### PubSub
155
156 This library is commonly used to efficiently transport messages using Redis'
157 [Pub/Sub](https://redis.io/topics/pubsub) (Publish/Subscribe) channels. For
158 instance, this can be used to distribute single messages to a larger number
159 of subscribers (think horizontal scaling for chat-like applications) or as an
160 efficient message transport in distributed systems (microservice architecture).
161
162 The [`PUBLISH` command](https://redis.io/commands/publish) can be used to
163 send a message to all clients currently subscribed to a given channel:
164
165 ```php
166 $channel = 'user';
167 $message = json_encode(array('id' => 10));
168 $redis->publish($channel, $message);
169 ```
170
171 The [`SUBSCRIBE` command](https://redis.io/commands/subscribe) can be used to
172 subscribe to a channel and then receive incoming PubSub `message` events:
173
174 ```php
175 $channel = 'user';
176 $redis->subscribe($channel);
177
178 $redis->on('message', function ($channel, $payload) {
179 // pubsub message received on given $channel
180 var_dump($channel, json_decode($payload));
181 });
182 ```
183
184 Likewise, you can use the same client connection to subscribe to multiple
185 channels by simply executing this command multiple times:
186
187 ```php
188 $redis->subscribe('user.register');
189 $redis->subscribe('user.join');
190 $redis->subscribe('user.leave');
191 ```
192
193 Similarly, the [`PSUBSCRIBE` command](https://redis.io/commands/psubscribe) can
194 be used to subscribe to all channels matching a given pattern and then receive
195 all incoming PubSub messages with the `pmessage` event:
196
197
198 ```php
199 $pattern = 'user.*';
200 $redis->psubscribe($pattern);
201
202 $redis->on('pmessage', function ($pattern, $channel, $payload) {
203 // pubsub message received matching given $pattern
204 var_dump($channel, json_decode($payload));
205 });
206 ```
207
208 Once you're in a subscribed state, Redis no longer allows executing any other
209 commands on the same client connection. This is commonly worked around by simply
210 creating a second client connection and dedicating one client connection solely
211 for PubSub subscriptions and the other for all other commands.
212
213 The [`UNSUBSCRIBE` command](https://redis.io/commands/unsubscribe) and
214 [`PUNSUBSCRIBE` command](https://redis.io/commands/punsubscribe) can be used to
215 unsubscribe from active subscriptions if you're no longer interested in
216 receiving any further events for the given channel and pattern subscriptions
217 respectively:
218
219 ```php
220 $redis->subscribe('user');
221
222 Loop::addTimer(60.0, function () use ($redis) {
223 $redis->unsubscribe('user');
224 });
225 ```
226
227 Likewise, once you've unsubscribed the last channel and pattern, the client
228 connection is no longer in a subscribed state and you can issue any other
229 command over this client connection again.
230
231 Each of the above methods follows normal request-response semantics and return
232 a [`Promise`](#promises) to await successful subscriptions. Note that while
233 Redis allows a variable number of arguments for each of these commands, this
234 library is currently limited to single arguments for each of these methods in
235 order to match exactly one response to each command request. As an alternative,
236 the methods can simply be invoked multiple times with one argument each.
237
238 Additionally, can listen for the following PubSub events to get notifications
239 about subscribed/unsubscribed channels and patterns:
240
241 ```php
242 $redis->on('subscribe', function ($channel, $total) {
243 // subscribed to given $channel
244 });
245 $redis->on('psubscribe', function ($pattern, $total) {
246 // subscribed to matching given $pattern
247 });
248 $redis->on('unsubscribe', function ($channel, $total) {
249 // unsubscribed from given $channel
250 });
251 $redis->on('punsubscribe', function ($pattern, $total) {
252 // unsubscribed from matching given $pattern
253 });
254 ```
255
256 When using the [`createLazyClient()`](#createlazyclient) method, the `unsubscribe`
257 and `punsubscribe` events will be invoked automatically when the underlying
258 connection is lost. This gives you control over re-subscribing to the channels
259 and patterns as appropriate.
260
261 ## API
262
263 ### Factory
264
265 The `Factory` is responsible for creating your [`Client`](#client) instance.
266
267 ```php
268 $factory = new Clue\React\Redis\Factory();
269 ```
270
271 This class takes an optional `LoopInterface|null $loop` parameter that can be used to
272 pass the event loop instance to use for this object. You can use a `null` value
273 here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
274 This value SHOULD NOT be given unless you're sure you want to explicitly use a
275 given event loop instance.
276
277 If you need custom connector settings (DNS resolution, TLS parameters, timeouts,
278 proxy servers etc.), you can explicitly pass a custom instance of the
279 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface):
280
281 ```php
282 $connector = new React\Socket\Connector(array(
283 'dns' => '127.0.0.1',
284 'tcp' => array(
285 'bindto' => '192.168.10.1:0'
286 ),
287 'tls' => array(
288 'verify_peer' => false,
289 'verify_peer_name' => false
290 )
291 ));
292
293 $factory = new Clue\React\Redis\Factory(null, $connector);
294 ```
295
296 #### createClient()
297
298 The `createClient(string $uri): PromiseInterface<Client,Exception>` method can be used to
299 create a new [`Client`](#client).
300
301 It helps with establishing a plain TCP/IP or secure TLS connection to Redis
302 and optionally authenticating (AUTH) and selecting the right database (SELECT).
303
304 ```php
305 $factory->createClient('localhost:6379')->then(
306 function (Client $redis) {
307 // client connected (and authenticated)
308 },
309 function (Exception $e) {
310 // an error occurred while trying to connect (or authenticate) client
311 }
312 );
313 ```
314
315 The method returns a [Promise](https://github.com/reactphp/promise) that
316 will resolve with a [`Client`](#client)
317 instance on success or will reject with an `Exception` if the URL is
318 invalid or the connection or authentication fails.
319
320 The returned Promise is implemented in such a way that it can be
321 cancelled when it is still pending. Cancelling a pending promise will
322 reject its value with an Exception and will cancel the underlying TCP/IP
323 connection attempt and/or Redis authentication.
324
325 ```php
326 $promise = $factory->createClient($uri);
327
328 Loop::addTimer(3.0, function () use ($promise) {
329 $promise->cancel();
330 });
331 ```
332
333 The `$redisUri` can be given in the
334 [standard](https://www.iana.org/assignments/uri-schemes/prov/redis) form
335 `[redis[s]://][:auth@]host[:port][/db]`.
336 You can omit the URI scheme and port if you're connecting to the default port 6379:
337
338 ```php
339 // both are equivalent due to defaults being applied
340 $factory->createClient('localhost');
341 $factory->createClient('redis://localhost:6379');
342 ```
343
344 Redis supports password-based authentication (`AUTH` command). Note that Redis'
345 authentication mechanism does not employ a username, so you can pass the
346 password `h@llo` URL-encoded (percent-encoded) as part of the URI like this:
347
348 ```php
349 // all forms are equivalent
350 $factory->createClient('redis://:h%40llo@localhost');
351 $factory->createClient('redis://ignored:h%40llo@localhost');
352 $factory->createClient('redis://localhost?password=h%40llo');
353 ```
354
355 You can optionally include a path that will be used to select (SELECT command) the right database:
356
357 ```php
358 // both forms are equivalent
359 $factory->createClient('redis://localhost/2');
360 $factory->createClient('redis://localhost?db=2');
361 ```
362
363 You can use the [standard](https://www.iana.org/assignments/uri-schemes/prov/rediss)
364 `rediss://` URI scheme if you're using a secure TLS proxy in front of Redis:
365
366 ```php
367 $factory->createClient('rediss://redis.example.com:6340');
368 ```
369
370 You can use the `redis+unix://` URI scheme if your Redis instance is listening
371 on a Unix domain socket (UDS) path:
372
373 ```php
374 $factory->createClient('redis+unix:///tmp/redis.sock');
375
376 // the URI MAY contain `password` and `db` query parameters as seen above
377 $factory->createClient('redis+unix:///tmp/redis.sock?password=secret&db=2');
378
379 // the URI MAY contain authentication details as userinfo as seen above
380 // should be used with care, also note that database can not be passed as path
381 $factory->createClient('redis+unix://:secret@/tmp/redis.sock');
382 ```
383
384 This method respects PHP's `default_socket_timeout` setting (default 60s)
385 as a timeout for establishing the connection and waiting for successful
386 authentication. You can explicitly pass a custom timeout value in seconds
387 (or use a negative number to not apply a timeout) like this:
388
389 ```php
390 $factory->createClient('localhost?timeout=0.5');
391 ```
392
393 #### createLazyClient()
394
395 The `createLazyClient(string $uri): Client` method can be used to
396 create a new [`Client`](#client).
397
398 It helps with establishing a plain TCP/IP or secure TLS connection to Redis
399 and optionally authenticating (AUTH) and selecting the right database (SELECT).
400
401 ```php
402 $redis = $factory->createLazyClient('localhost:6379');
403
404 $redis->incr('hello');
405 $redis->end();
406 ```
407
408 This method immediately returns a "virtual" connection implementing the
409 [`Client`](#client) that can be used to interface with your Redis database.
410 Internally, it lazily creates the underlying database connection only on
411 demand once the first request is invoked on this instance and will queue
412 all outstanding requests until the underlying connection is ready.
413 Additionally, it will only keep this underlying connection in an "idle" state
414 for 60s by default and will automatically close the underlying connection when
415 it is no longer needed.
416
417 From a consumer side this means that you can start sending commands to the
418 database right away while the underlying connection may still be
419 outstanding. Because creating this underlying connection may take some
420 time, it will enqueue all oustanding commands and will ensure that all
421 commands will be executed in correct order once the connection is ready.
422 In other words, this "virtual" connection behaves just like a "real"
423 connection as described in the `Client` interface and frees you from having
424 to deal with its async resolution.
425
426 If the underlying database connection fails, it will reject all
427 outstanding commands and will return to the initial "idle" state. This
428 means that you can keep sending additional commands at a later time which
429 will again try to open a new underlying connection. Note that this may
430 require special care if you're using transactions (`MULTI`/`EXEC`) that are kept
431 open for longer than the idle period.
432
433 While using PubSub channels (see `SUBSCRIBE` and `PSUBSCRIBE` commands), this client
434 will never reach an "idle" state and will keep pending forever (or until the
435 underlying database connection is lost). Additionally, if the underlying
436 database connection drops, it will automatically send the appropriate `unsubscribe`
437 and `punsubscribe` events for all currently active channel and pattern subscriptions.
438 This allows you to react to these events and restore your subscriptions by
439 creating a new underlying connection repeating the above commands again.
440
441 Note that creating the underlying connection will be deferred until the
442 first request is invoked. Accordingly, any eventual connection issues
443 will be detected once this instance is first used. You can use the
444 `end()` method to ensure that the "virtual" connection will be soft-closed
445 and no further commands can be enqueued. Similarly, calling `end()` on
446 this instance when not currently connected will succeed immediately and
447 will not have to wait for an actual underlying connection.
448
449 Depending on your particular use case, you may prefer this method or the
450 underlying `createClient()` which resolves with a promise. For many
451 simple use cases it may be easier to create a lazy connection.
452
453 The `$redisUri` can be given in the
454 [standard](https://www.iana.org/assignments/uri-schemes/prov/redis) form
455 `[redis[s]://][:auth@]host[:port][/db]`.
456 You can omit the URI scheme and port if you're connecting to the default port 6379:
457
458 ```php
459 // both are equivalent due to defaults being applied
460 $factory->createLazyClient('localhost');
461 $factory->createLazyClient('redis://localhost:6379');
462 ```
463
464 Redis supports password-based authentication (`AUTH` command). Note that Redis'
465 authentication mechanism does not employ a username, so you can pass the
466 password `h@llo` URL-encoded (percent-encoded) as part of the URI like this:
467
468 ```php
469 // all forms are equivalent
470 $factory->createLazyClient('redis://:h%40llo@localhost');
471 $factory->createLazyClient('redis://ignored:h%40llo@localhost');
472 $factory->createLazyClient('redis://localhost?password=h%40llo');
473 ```
474
475 You can optionally include a path that will be used to select (SELECT command) the right database:
476
477 ```php
478 // both forms are equivalent
479 $factory->createLazyClient('redis://localhost/2');
480 $factory->createLazyClient('redis://localhost?db=2');
481 ```
482
483 You can use the [standard](https://www.iana.org/assignments/uri-schemes/prov/rediss)
484 `rediss://` URI scheme if you're using a secure TLS proxy in front of Redis:
485
486 ```php
487 $factory->createLazyClient('rediss://redis.example.com:6340');
488 ```
489
490 You can use the `redis+unix://` URI scheme if your Redis instance is listening
491 on a Unix domain socket (UDS) path:
492
493 ```php
494 $factory->createLazyClient('redis+unix:///tmp/redis.sock');
495
496 // the URI MAY contain `password` and `db` query parameters as seen above
497 $factory->createLazyClient('redis+unix:///tmp/redis.sock?password=secret&db=2');
498
499 // the URI MAY contain authentication details as userinfo as seen above
500 // should be used with care, also note that database can not be passed as path
501 $factory->createLazyClient('redis+unix://:secret@/tmp/redis.sock');
502 ```
503
504 This method respects PHP's `default_socket_timeout` setting (default 60s)
505 as a timeout for establishing the underlying connection and waiting for
506 successful authentication. You can explicitly pass a custom timeout value
507 in seconds (or use a negative number to not apply a timeout) like this:
508
509 ```php
510 $factory->createLazyClient('localhost?timeout=0.5');
511 ```
512
513 By default, this method will keep "idle" connections open for 60s and will
514 then end the underlying connection. The next request after an "idle"
515 connection ended will automatically create a new underlying connection.
516 This ensure you always get a "fresh" connection and as such should not be
517 confused with a "keepalive" or "heartbeat" mechanism, as this will not
518 actively try to probe the connection. You can explicitly pass a custom
519 idle timeout value in seconds (or use a negative number to not apply a
520 timeout) like this:
521
522 ```php
523 $factory->createLazyClient('localhost?idle=0.1');
524 ```
525
526 ### Client
527
528 The `Client` is responsible for exchanging messages with Redis
529 and keeps track of pending commands.
530
531 Besides defining a few methods, this interface also implements the
532 `EventEmitterInterface` which allows you to react to certain events as documented below.
533
534 #### __call()
535
536 The `__call(string $name, string[] $args): PromiseInterface<mixed,Exception>` method can be used to
537 invoke the given command.
538
539 This is a magic method that will be invoked when calling any Redis command on this instance.
540 Each method call matches the respective [Redis command](https://redis.io/commands).
541 For example, the `$redis->get()` method will invoke the [`GET` command](https://redis.io/commands/get).
542
543 ```php
544 $redis->get($key)->then(function (?string $value) {
545 var_dump($value);
546 }, function (Exception $e) {
547 echo 'Error: ' . $e->getMessage() . PHP_EOL;
548 });
549 ```
550
551 All [Redis commands](https://redis.io/commands) are automatically available as
552 public methods via this magic `__call()` method.
553 Listing all available commands is out of scope here, please refer to the
554 [Redis command reference](https://redis.io/commands).
555
556 Any arguments passed to the method call will be forwarded as command arguments.
557 For example, the `$redis->set('name', 'Alice')` call will perform the equivalent of a
558 `SET name Alice` command. It's safe to pass integer arguments where applicable (for
559 example `$redis->expire($key, 60)`), but internally Redis requires all arguments to
560 always be coerced to string values.
561
562 Each of these commands supports async operation and returns a [Promise](#promises)
563 that eventually *fulfills* with its *results* on success or *rejects* with an
564 `Exception` on error. See also [promises](#promises) for more details.
565
566 #### end()
567
568 The `end():void` method can be used to
569 soft-close the Redis connection once all pending commands are completed.
570
571 #### close()
572
573 The `close():void` method can be used to
574 force-close the Redis connection and reject all pending commands.
575
576 #### error event
577
578 The `error` event will be emitted once a fatal error occurs, such as
579 when the client connection is lost or is invalid.
580 The event receives a single `Exception` argument for the error instance.
581
582 ```php
583 $redis->on('error', function (Exception $e) {
584 echo 'Error: ' . $e->getMessage() . PHP_EOL;
585 });
586 ```
587
588 This event will only be triggered for fatal errors and will be followed
589 by closing the client connection. It is not to be confused with "soft"
590 errors caused by invalid commands.
591
592 #### close event
593
594 The `close` event will be emitted once the client connection closes (terminates).
595
596 ```php
597 $redis->on('close', function () {
598 echo 'Connection closed' . PHP_EOL;
599 });
600 ```
601
602 See also the [`close()`](#close) method.
603
604 ## Install
605
606 The recommended way to install this library is [through Composer](https://getcomposer.org/).
607 [New to Composer?](https://getcomposer.org/doc/00-intro.md)
608
609 This project follows [SemVer](https://semver.org/).
610 This will install the latest supported version:
611
612 ```bash
613 $ composer require clue/redis-react:^2.8
614 ```
615
616 See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.
617
618 This project aims to run on any platform and thus does not require any PHP
619 extensions and supports running on legacy PHP 5.3 through current PHP 8+ and
620 HHVM.
621 It's *highly recommended to use the latest supported PHP version* for this project.
622
623 ## Tests
624
625 To run the test suite, you first need to clone this repo and then install all
626 dependencies [through Composer](https://getcomposer.org/):
627
628 ```bash
629 $ composer install
630 ```
631
632 To run the test suite, go to the project root and run:
633
634 ```bash
635 $ vendor/bin/phpunit
636 ```
637
638 The test suite contains both unit tests and functional integration tests.
639 The functional tests require access to a running Redis server instance
640 and will be skipped by default.
641
642 If you don't have access to a running Redis server, you can also use a temporary `Redis` Docker image:
643
644 ```bash
645 $ docker run --net=host redis
646 ```
647
648 To now run the functional tests, you need to supply *your* login
649 details in an environment variable like this:
650
651 ```bash
652 $ REDIS_URI=localhost:6379 vendor/bin/phpunit
653 ```
654
655 ## License
656
657 This project is released under the permissive [MIT license](LICENSE).
658
659 > Did you know that I offer custom development services and issuing invoices for
660 sponsorships of releases and for contributions? Contact me (@clue) for details.