blib/lib/EV/Redis.pm

filter: Statementstmt 96.2% 76 / 79 Branchbran 74.2% 52 / 70 Conditioncond 60.0% 15 / 25 MC/DCmcdc 12.5% 2 / 16 Subroutinesub 80.0% 12 / 15 Podpod 25.0% 1 / 4 totaltotal 75.6% 158 / 209 CC 45 SCAR 38.2
CC
45
Cov
82%
new
60.5
AUTOLOAD
2.0
CLONE_SKIP
2.0
CRAP 45.5
↑ Summary deps/hiredis/alloc.h »
1 package EV::Redis;
2 54 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 54 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 54 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 54 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 54 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
9 54 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 54 our $VERSION = '0.16';
11 54 XSLoader::load __PACKAGE__, $VERSION;
12 }
13  
14 54 my %new_option = map { $_ => 1 } qw(
15 host port path loop on_error on_connect on_disconnect on_push
16 connect_timeout command_timeout max_pending waiting_timeout
17 resume_waiting_on_reconnect priority keepalive prefer_ipv4 prefer_ipv6
18 source_addr tcp_user_timeout cloexec reuseaddr reconnect reconnect_delay
19 max_reconnect_attempts tls tls_ca tls_capath tls_cert tls_key
20 tls_server_name tls_verify
21 );
22  
23 72 ▶sub new {
Subroutine new: called CC=44 SCAR=41.0
Pod documented
24 72 my ($class, %args) = @_;
25  
26 # a subclass may pass options of its own
27 72 ▶ if ((ref $class || $class) eq __PACKAGE__) {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $class || $class) eq __PACKAGE__) 71 1 72
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0720
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
28 71 my @unknown = sort grep { !$new_option{$_} } keys %args;
29 71 ▶ Carp::carp("EV::Redis->new: unknown option(s): @unknown") if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 0 71 71
30 Carp::carp("EV::Redis->new: 'port' has no effect without 'host'")
31 71 ▶ if defined $args{port} && !exists $args{host};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"port"} and not exists $args{"host"} 0 71 71
Condition66%2/3
defined $args{"port"} and not exists $args{"host"}
!ll&&!rl&&r
6560
MC/DC0%0/2
defined $args{"port"} and not exists $args{"host"}
defined $args{"port"} not exists $args{"host"}
Truth table66%2/3
A and not(B)
A= defined $args{"port"}B= not exists $args{"host"}
ABresult
0X0
100
111
32 71 ▶ if (!$args{tls}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"tls"}) 67 4 71
33 67 my @tls_only = grep { defined $args{$_} }
34 qw(tls_ca tls_capath tls_cert tls_key tls_server_name tls_verify);
35 67 ▶ Carp::carp("EV::Redis->new: TLS options (@tls_only) have no effect without 'tls'")
Branch: 1 branch
BranchTrueFalseTotal
if @tls_only 0 67 67
36 if @tls_only;
37 }
38 }
39  
40 Carp::croak("Cannot specify both 'host' and 'path'")
41 72 ▶ if exists $args{host} && exists $args{path};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"host"} and exists $args{"path"} 0 72 72
Condition66%2/3
exists $args{"host"} and exists $args{"path"}
!ll&&!rl&&r
6660
MC/DC0%0/2
exists $args{"host"} and exists $args{"path"}
exists $args{"host"} exists $args{"path"}
Truth table66%2/3
A and B
A= exists $args{"host"}B= exists $args{"path"}
ABresult
0X0
100
111
42 Carp::croak("Cannot specify both 'prefer_ipv4' and 'prefer_ipv6'")
43 72 ▶ if $args{prefer_ipv4} && $args{prefer_ipv6};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"prefer_ipv4"} and $args{"prefer_ipv6"} 0 72 72
Condition66%2/3
$args{"prefer_ipv4"} and $args{"prefer_ipv6"}
!ll&&!rl&&r
7110
MC/DC0%0/2
$args{"prefer_ipv4"} and $args{"prefer_ipv6"}
$args{"prefer_ipv4"} $args{"prefer_ipv6"}
Truth table66%2/3
A and B
A= $args{"prefer_ipv4"}B= $args{"prefer_ipv6"}
ABresult
0X0
100
111
44  
45 72 ▶ my $loop = $args{loop} // EV::default_loop;
Condition33%1/3
$args{"loop"} // &EV::default_loop()
l!l&&r!l&&!r
0720
MC/DC0%0/2
$args{"loop"} // &EV::default_loop()
$args{"loop"} &EV::default_loop()
Truth table33%1/3
A // B
A= $args{"loop"}B= &EV::default_loop()
ABresult
1X1
011
000
46 72 ▶ my $self = bless $class->_new($loop), ref $class || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0720
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
47  
48 0 ▶ $self->on_error($args{on_error} // sub { die "$_[0]\n" });
Subroutine __ANON__: not called CC=1 SCAR=0.6
Condition66%2/3
$args{"on_error"} // sub { die "$_[0]\n"; }
l!l&&r!l&&!r
53190
MC/DC0%0/2
$args{"on_error"} // sub { die "$_[0]\n"; }
$args{"on_error"} sub { die "$_[0]\n"; }
Truth table66%2/3
A // B
A= $args{"on_error"}B= sub { die "$_[0]\n"; }
ABresult
1X1
011
000
49 72 ▶ $self->on_connect($args{on_connect}) if exists $args{on_connect};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_connect"} 19 53 72
50 72 ▶ $self->on_disconnect($args{on_disconnect}) if exists $args{on_disconnect};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_disconnect"} 10 62 72
51 72 ▶ $self->on_push($args{on_push}) if exists $args{on_push};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"on_push"} 0 72 72
52 72 ▶ $self->connect_timeout($args{connect_timeout}) if defined $args{connect_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"connect_timeout"} 5 67 72
53 72 ▶ $self->command_timeout($args{command_timeout}) if defined $args{command_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"command_timeout"} 14 58 72
54 72 ▶ $self->max_pending($args{max_pending}) if defined $args{max_pending};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"max_pending"} 0 72 72
55 72 ▶ $self->waiting_timeout($args{waiting_timeout}) if defined $args{waiting_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"waiting_timeout"} 0 72 72
56 72 ▶ $self->resume_waiting_on_reconnect($args{resume_waiting_on_reconnect}) if defined $args{resume_waiting_on_reconnect};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"resume_waiting_on_reconnect"} 5 67 72
57 72 ▶ $self->priority($args{priority}) if defined $args{priority};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"priority"} 1 71 72
58 72 ▶ $self->keepalive($args{keepalive}) if defined $args{keepalive};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"keepalive"} 0 72 72
59 72 ▶ $self->prefer_ipv4($args{prefer_ipv4}) if exists $args{prefer_ipv4};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"prefer_ipv4"} 1 71 72
60 72 ▶ $self->prefer_ipv6($args{prefer_ipv6}) if exists $args{prefer_ipv6};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"prefer_ipv6"} 1 71 72
61 72 ▶ $self->source_addr($args{source_addr}) if defined $args{source_addr};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"source_addr"} 0 72 72
62 72 ▶ $self->tcp_user_timeout($args{tcp_user_timeout}) if defined $args{tcp_user_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"tcp_user_timeout"} 2 70 72
63 72 ▶ $self->cloexec($args{cloexec}) if exists $args{cloexec};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"cloexec"} 0 72 72
64 72 ▶ $self->reuseaddr($args{reuseaddr}) if exists $args{reuseaddr};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"reuseaddr"} 0 72 72
65  
66 72 ▶ if ($args{reconnect}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"reconnect"}) 13 59 72
67 $self->reconnect(
68 1,
69 $args{reconnect_delay} // 1000,
70 13 ▶ $args{max_reconnect_attempts} // 0
Condition100%4/4
$args{"reconnect_delay"} // 1000
l!l
112
$args{"max_reconnect_attempts"} // 0
l!l
67
MC/DC100%1/1
$args{"reconnect_delay"} // 1000
$args{"reconnect_delay"}
MC/DC100%1/1
$args{"max_reconnect_attempts"} // 0
$args{"max_reconnect_attempts"}
Truth table100%2/2
A
A= $args{"reconnect_delay"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"max_reconnect_attempts"}
Aresult
11
00
71 );
72 }
73  
74 # TLS context must be set up before connect
75 72 ▶ if ($args{tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"tls"}) 4 68 72
76 4 ▶ Carp::croak("TLS support not compiled in; rebuild with EV_REDIS_SSL=1")
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_ssl 0 4 4
77 unless $self->has_ssl;
78 Carp::croak("TLS requires 'host' parameter (not 'path')")
79 4 ▶ if exists $args{path};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"path"} 1 3 4
80 $self->_setup_ssl_context(
81 $args{tls_ca}, $args{tls_capath}, $args{tls_cert}, $args{tls_key},
82 $args{tls_server_name},
83 3 ▶ exists $args{tls_verify} ? ($args{tls_verify} ? 1 : 0) : 1,
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'tls_verify'} ? : 1 2 3
$args{'tls_verify'} ? : 0 1 1
84 );
85 }
86  
87 70 ▶ if (exists $args{host}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $args{'host'}) { } 6 64 70
elsif (exists $args{'path'}) { } 3 61 64
88 6 ▶ Carp::croak("'host' must be a defined string") unless defined $args{host};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"host"} 0 6 6
89 defined $args{port}
90 ? $self->connect($args{host}, $args{port})
91 6 ▶ : $self->connect($args{host});
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'port'} ? : 6 0 6
92 }
93 elsif (exists $args{path}) {
94 3 ▶ Carp::croak("'path' must be a defined string") unless defined $args{path};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"path"} 0 3 3
95 3 $self->connect_unix($args{path});
96 }
97  
98 69 $self;
99 }
100  
101 # the XS object is a bare C pointer, meaningless in another interpreter
102 0 ▶sub CLONE_SKIP { 1 }
Subroutine CLONE_SKIP: not called CC=1 SCAR=6.9
103  
104 # a thawed copy would carry the same pointer and free it with the original
105 1 ▶sub STORABLE_freeze { Carp::croak("EV::Redis objects cannot be serialized") }
Subroutine STORABLE_freeze: called CC=1 SCAR=0.0
Pod undocumented
106  
107 # Sereal uses its own hooks; a thawed copy would alias a live object or dangle
108 1 ▶sub FREEZE { Carp::croak("EV::Redis objects cannot be serialized") }
Subroutine FREEZE: called CC=1 SCAR=0.0
Pod undocumented
109 0 ▶sub THAW { Carp::croak("EV::Redis objects cannot be serialized") }
Subroutine THAW: not called CC=1 SCAR=6.9
Pod undocumented
110  
111 54 our $AUTOLOAD;
112  
113 12 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=2 SCAR=6.9
114 12 (my $method = $AUTOLOAD) =~ s/.*:://;
115 12 ▶ return if $method eq 'DESTROY';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 0 12 12
116  
117 44 ▶ my $sub = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
118 44 my $self = shift;
119 44 $self->command($method, @_);
120 12 };
121  
122 54 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
123 12 *$method = $sub;
124 12 goto $sub;
125 }
126  
127 54 1;
128  
129 =head1 NAME
130  
131 EV::Redis - Asynchronous redis client using hiredis and EV
132  
133 =head1 SYNOPSIS
134  
135 use EV::Redis;
136
137 my $redis = EV::Redis->new;
138 $redis->connect('127.0.0.1');
139
140 # or
141 my $redis = EV::Redis->new( host => '127.0.0.1' );
142
143 # command
144 $redis->set('foo' => 'bar', sub {
145 my ($res, $err) = @_;
146
147 print $res; # OK
148
149 $redis->get('foo', sub {
150 my ($res, $err) = @_;
151
152 print $res; # bar
153
154 $redis->disconnect;
155 });
156 });
157
158 # start main loop
159 EV::run;
160  
161 =head1 DESCRIPTION
162  
163 EV::Redis is a fork of L<EV::Hiredis> by Daisuke Murase (typester),
164 extended with reconnection, flow control, TLS, and RESP3 support. It is a
165 drop-in replacement for EV::Hiredis, except that commands which would pair
166 replies with the wrong callbacks croak (see B<Reply order note>).
167  
168 This is an asynchronous client for Redis using hiredis and L<EV> as backend.
169 It connects to L<EV> with C-level interface so that it runs faster.
170  
171 =head1 ANYEVENT INTEGRATION
172  
173 L<AnyEvent> has a support for EV as its one of backends, so L<EV::Redis> can be used in your AnyEvent applications seamlessly.
174  
175 =head1 NO UTF-8 SUPPORT
176  
177 Unlike other redis modules, this module doesn't support utf-8 string.
178  
179 This module handles all values as bytes: a string with characters above
180 C<0xFF> croaks with a "Wide character" error. Encode utf-8 strings before
181 passing them:
182  
183 use Encode;
184
185 # set $val
186 $redis->set(foo => encode_utf8 $val, sub { ... });
187
188 # get $val
189 $redis->get('foo', sub {
190 my $val = decode_utf8 $_[0];
191 });
192  
193 =head1 SIGPIPE
194  
195 Writing to a connection the server has closed raises C<SIGPIPE>, which
196 kills the process by default. Set C<$SIG{PIPE} = 'IGNORE'> to get the error
197 in C<on_error> instead.
198  
199 =head1 FORK
200  
201 A child process must not use an inherited object: its connection fails in
202 the child with "connection inherited from the parent process" (with
203 C<reconnect>, the child then connects on its own); the parent is not
204 affected. A loop other than the default needs C<< $loop->loop_fork >> in the
205 child. Do not fork inside a callback. Objects cannot be copied: C<Storable>
206 and C<Sereal> with C<freeze_callbacks> croak on them. Other serialized or
207 C<Clone> copies are inert: their methods croak and destroying them does nothing.
208  
209 =head1 RESP3 REPLIES
210  
211 After C<HELLO 3>, maps and sets arrive as array references (a map as a flat
212 key, value list), doubles as numbers, booleans as 1 or 0, and big numbers and
213 verbatim strings as plain strings. Attribute replies are not supported: one
214 ahead of a reply is dropped, one inside an array or map fails the connection.
215  
216 =head1 METHODS
217  
218 =head2 new(%options);
219  
220 Create new L<EV::Redis> instance.
221  
222 Available C<%options> are:
223  
224 =over
225  
226 =item * host => 'Str'
227  
228 =item * port => 'Int'
229  
230 Hostname and port number of redis-server to connect. Mutually exclusive with C<path>.
231  
232 =item * path => 'Str'
233  
234 UNIX socket path to connect. Mutually exclusive with C<host>.
235  
236 =item * on_error => $cb->($errstr)
237  
238 Called on connection-level errors. The default handler dies, but exceptions
239 thrown in handlers and command callbacks are caught and reported as
240 warnings, so connection errors become warnings unless you install your own.
241 C<undef> here keeps the default; C<< on_error(undef) >> removes it.
242 They never end C<EV::run>, including one from a C<%SIG> handler such as
243 C<alarm>: use C<command_timeout> or an C<EV::timer> for timeouts.
244  
245 =item * on_connect => $cb->()
246  
247 Called when the connection is established (with C<tls>, once TCP is up; a
248 failed handshake then arrives as C<on_error>).
249  
250 =item * on_disconnect => $cb->()
251  
252 Called when the connection closes, normally or on error.
253  
254 =item * on_push => $cb->($reply)
255  
256 Called with RESP3 push messages (Redis 6.0+), as an array reference.
257  
258 The handlers can be set later with the methods of the same name.
259  
260 =item * connect_timeout => $num_of_milliseconds
261  
262 Connection timeout.
263  
264 =item * command_timeout => $num_of_milliseconds
265  
266 Command timeout.
267  
268 =item * max_pending => $num
269  
270 =item * waiting_timeout => $num_of_milliseconds
271  
272 See the methods of the same name.
273  
274 =item * resume_waiting_on_reconnect => $bool
275  
276 If true and C<reconnect> is on, commands waiting locally are kept across a
277 lost connection and sent after reconnecting. Otherwise (the default) a lost
278 connection or failed connect attempt cancels them. C<disconnect()>, or giving
279 up on reconnecting, cancels them either way. A transaction does not survive:
280 commands issued inside C<WATCH>/C<MULTI>..C<EXEC> are replayed only when none
281 of the transaction reached the server, and fail with the lost connection
282 otherwise.
283  
284 =item * reconnect => $bool
285  
286 Enable automatic reconnection on connection failure or unexpected disconnection.
287 Default is disabled (0).
288  
289 =item * reconnect_delay => $num_of_milliseconds
290  
291 Delay between reconnection attempts. Default is 1000 (1 second). Used only
292 with C<reconnect>, as is C<max_reconnect_attempts>.
293  
294 =item * max_reconnect_attempts => $num
295  
296 Maximum number of reconnect attempts in a row; an established connection
297 resets the count. 0 (default) means unlimited.
298  
299 =item * priority => $num
300  
301 Priority for the underlying libev IO watchers. Higher priority watchers are
302 invoked before lower priority ones. Valid range is -2 (lowest) to +2 (highest),
303 with 0 being the default. See L<EV> documentation for details on priorities.
304  
305 =item * keepalive => $seconds
306  
307 Enable TCP keepalive probes on idle connections, with this interval in
308 seconds (at most 32767; the interval itself is set with glibc and on macOS
309 only).
310 0 means disabled (default). Ignored for unix sockets.
311  
312 =item * prefer_ipv4 => $bool
313  
314 =item * prefer_ipv6 => $bool
315  
316 Resolve host names to that address family, falling back to the other only
317 when the name has no address of it. IPv4 is the default.
318  
319 =item * source_addr => 'Str'
320  
321 Local address to bind the outbound connection to. Useful on multi-homed
322 servers to select a specific network interface. Ignored for unix sockets.
323  
324 =item * tcp_user_timeout => $num_of_milliseconds
325  
326 Set TCP_USER_TIMEOUT (Linux): how long sent data may stay unacknowledged
327 before the connection is dropped. Ignored for unix sockets; where the system
328 lacks the option, TCP connects fail.
329  
330 =item * cloexec => $bool
331  
332 Set close-on-exec on the Redis connection socket. Prevents the file descriptor
333 from leaking to child processes after fork/exec. Default is enabled.
334  
335 =item * reuseaddr => $bool
336  
337 Set SO_REUSEADDR on the Redis connection socket. Allows rebinding to an
338 address that is still in TIME_WAIT state. Default is disabled. Only takes
339 effect with C<source_addr>.
340  
341 =item * tls => $bool
342  
343 Enable TLS/SSL encryption for the connection. Requires that the module was
344 built with TLS support (auto-detected at build time, or forced with
345 C<EV_REDIS_SSL=1>). Only valid with C<host> connections, not C<path>.
346  
347 =item * tls_ca => 'Str'
348  
349 Path to CA certificate file for server verification. If not specified,
350 uses the system default CA store.
351  
352 =item * tls_capath => 'Str'
353  
354 Path to a directory containing CA certificate files in OpenSSL-compatible
355 format (hashed filenames). Alternative to C<tls_ca> for multiple CA certs.
356  
357 =item * tls_cert => 'Str'
358  
359 Path to client certificate file for mutual TLS authentication. Must be
360 specified together with C<tls_key>.
361  
362 =item * tls_key => 'Str'
363  
364 Path to client private key file. Must be specified together with C<tls_cert>.
365  
366 =item * tls_server_name => 'Str'
367  
368 Server name for SNI, sent on every connection; without it no SNI is sent. It
369 is not checked against the certificate.
370  
371 =item * tls_verify => $bool
372  
373 Verify the server certificate (default true). Only the chain is checked, not
374 the host name, so use C<tls_ca> with a CA dedicated to your Redis servers
375 rather than the system store.
376  
377 =item * loop => 'EV::Loop',
378  
379 EV loop for running this instance. Default is C<EV::default_loop>.
380  
381 =back
382  
383 All parameters are optional. Unknown ones warn, unless C<new> is called
384 on a subclass.
385  
386 If parameters about connection (host&port or path) is not passed, you should call C<connect> or C<connect_unix> method by hand to connect to redis-server.
387  
388 =head2 connect($hostname [, $port])
389  
390 =head2 connect_unix($path)
391  
392 Connect to a redis-server for C<$hostname:$port> (default 6379) or C<$path>.
393 Croaks if a connection is already active or the port or path is invalid. A
394 failure found at once (a missing socket, a name that does not resolve)
395 reaches C<on_error> before it returns. Host names are resolved
396 synchronously, by each reconnect too, outside C<connect_timeout>: pass an IP
397 address where DNS can be slow.
398  
399 =head2 command($commands..., [$cb->($result, $error)])
400  
401 Do a redis command and return its result by callback. Returns C<REDIS_OK>
402 (0), or C<REDIS_ERR> (-1) if it could not be enqueued (the callback gets the
403 error too).
404  
405 $redis->command('get', 'foo', sub {
406 my ($result, $error) = @_;
407  
408 print $result; # value for key 'foo'
409 print $error; # redis error string, undef if no error
410 });
411  
412 On error, C<$error> holds the message and C<$result> is undef; otherwise
413 C<$error> is undef. An error inside an array reply (such as C<EXEC>'s result
414 for a failed queued command) arrives as its error text.
415  
416 The callback is optional: only a code reference in the last position is
417 taken as one, so an C<undef> there is sent as an argument. Without one the
418 command is fire-and-forget: its reply and errors are discarded (connection
419 errors still reach C<on_error>):
420  
421 $redis->set('counter', 42); # fire-and-forget, no callback
422  
423 With a million commands outstanding, a closure per command makes their
424 completion take minutes; share one code reference instead.
425  
426 All commands can also be called via the AUTOLOAD interface:
427  
428 $redis->command('get', 'foo', sub { ... });
429  
430 is equivalent to:
431  
432 $redis->get('foo', sub { ... });
433  
434 The Redis C<COMMAND> command itself is reached as
435 C<< $redis->command('command', ...) >>, since C<command> is this method.
436  
437 B<Note:> C<command()> croaks with "connection required before calling
438 command" while not connected, unless a reconnect is pending: commands then
439 wait locally (see C<resume_waiting_on_reconnect>). In C<on_error> and
440 C<on_disconnect> it still croaks, as the reconnect is scheduled after they
441 return. A retry issued from a failed command's callback waits for the
442 reconnect or fails in turn (after a failed connect with no reconnect
443 scheduled, it croaks); it never recurses.
444  
445 B<Pub/Sub note:> C<subscribe> and C<psubscribe> take at least one name and a
446 persistent callback, which also receives the unsubscribe confirmations (a
447 callback passed to C<unsubscribe> is ignored unless the command is refused).
448 Subscribing again to a name moves it to the new callback. An error reply on
449 a subscribed connection closes it, so keep pub/sub on a connection of its
450 own; set C<keepalive> to notice a server that vanished, as a subscribed
451 connection has no timeout. When the connection closes, a subscribe callback
452 gets one error for each channel or pattern it still holds. Sharded pub/sub (C<ssubscribe>, C<sunsubscribe>)
453 is not supported and croaks; C<spublish> works.
454  
455 B<MONITOR note:> C<monitor> requires an idle connection, so it cannot be
456 issued from within a reply callback; once it is active C<command()> croaks
457 on that connection. C<pmonitor> is not supported. Use a dedicated one.
458  
459 B<Reply order note:> hiredis hands each reply to the oldest waiting callback,
460 so commands that change how the server answers croak: C<CLIENT REPLY OFF>
461 and C<SKIP>, C<REPLCONF ACK> and C<GETACK>, C<SYNC>, C<PSYNC>, and C<RESET>
462 while subscribed. Pub/sub commands, C<monitor> and C<HELLO> inside C<MULTI>
463 fail through their callback; pub/sub and C<HELLO> first wait locally for
464 outstanding transaction replies, a round trip each. An C<EXEC> cancelled
465 before it was sent leaves the transaction open.
466  
467 B<Nested event loop note:> while a callback for an event on this connection
468 runs, its I/O is paused, so a nested C<EV::run> inside it cannot receive
469 replies for the same connection. Use a separate connection to wait for
470 Redis inside a callback.
471  
472 =head2 disconnect
473  
474 Disconnect from redis-server; safe when already disconnected. Stops any
475 pending reconnect and cancels waiting commands with "disconnected" before it
476 returns. Commands already sent are not cancelled (except on a subscribed
477 connection): the connection closes once they are answered, then
478 C<on_disconnect> runs. It runs only for a connection that was established.
479 So it does not drop a server that stopped answering:
480 use C<command_timeout>, or destroy the object. Sending C<QUIT> instead is
481 reported as a lost connection, and C<reconnect> connects again.
482  
483 =head2 is_connected
484  
485 Returns true (1) if a connection context is active (including while the
486 connection is being established), false (0) otherwise.
487  
488 =head2 has_ssl
489  
490 Class method. Returns true (1) if the module was built with TLS support,
491 false (0) otherwise.
492  
493 if (EV::Redis->has_ssl) {
494 # TLS connections are available
495 }
496  
497 =head2 connect_timeout([$ms])
498  
499 Get or set the connection timeout in milliseconds (C<0> disables; undef if
500 never set). It covers the connect attempt after name resolution; with
501 C<tls>, the TCP connect only (C<command_timeout> ends a stalled handshake
502 once a command is outstanding). Without it, a unix socket whose server has a
503 full listen queue is retried in a busy loop.
504  
505 =head2 command_timeout([$ms])
506  
507 Get or set the command timeout in milliseconds (C<0> disables; undef if
508 never set). It fires when replies are outstanding and nothing has arrived
509 for that long; new commands do not extend it, a large command going out
510 does. Subscriptions are not covered; an idle MONITOR connection times out.
511 A command that timed out, or lost its connection, may still have run, or
512 run later: retry only commands safe to run twice. Changes apply at once.
513  
514 =head2 on_error([$cb->($errstr)])
515  
516 Set the error callback. Like all handler methods (C<on_error>,
517 C<on_connect>, C<on_disconnect>, C<on_push>): a CODE reference replaces the
518 handler and is returned; C<undef> or no argument clears it (so the current
519 handler cannot be read); any other value clears it with a warning.
520  
521 =head2 on_connect([$cb->()])
522  
523 Set the connect callback. Commands issued from it go first, past
524 C<max_pending>, so it suits per-connection setup such as C<AUTH> or
525 C<SELECT>. Commands waiting locally go after that setup; one sent while the
526 connection was being established goes before it, unless both C<reconnect>
527 and C<resume_waiting_on_reconnect> are on.
528  
529 =head2 on_disconnect([$cb->()])
530  
531 Set the disconnect callback, called on both normal and error disconnections.
532  
533 =head2 on_push([$cb->($reply)])
534  
535 Set the RESP3 push callback (Redis 6.0+); it receives the push message as an
536 array reference.
537  
538 $redis->on_push(sub {
539 my ($msg) = @_;
540 # $msg is an array ref, e.g. ['invalidate', ['key1', 'key2']]
541 });
542  
543 =head2 reconnect($enable, $delay_ms, $max_attempts)
544  
545 Configure automatic reconnection.
546  
547 $redis->reconnect(1); # enable with defaults (1s delay, unlimited)
548 $redis->reconnect(1, 0); # enable with immediate reconnect
549 $redis->reconnect(1, 2000); # enable with 2 second delay
550 $redis->reconnect(1, 1000, 5); # enable with 1s delay, max 5 attempts
551 $redis->reconnect(0); # disable
552  
553 C<$delay_ms> defaults to 1000; 0 retries at once, in a busy loop against a
554 server that refuses connections. C<$max_attempts> defaults to 0 (unlimited).
555 Explicit undef keeps the current value of that argument.
556  
557 It reconnects after a failed connect or an unexpected disconnection, not
558 after C<disconnect()>. A new connection starts fresh: subscriptions,
559 C<AUTH>, C<SELECT> and C<HELLO> are not restored, so issue them from
560 C<on_connect>.
561  
562 =head2 reconnect_enabled
563  
564 Returns true (1) if automatic reconnection is enabled, false (0) otherwise.
565  
566 =head2 pending_count
567  
568 Returns the number of commands sent to Redis awaiting replies, not counting
569 (p)subscribe, (p)unsubscribe and monitor. Inside a reply callback the count
570 still includes that command.
571  
572 =head2 waiting_count
573  
574 Returns the number of commands queued locally, not yet sent: over
575 C<max_pending>, during a reconnect, or held for transaction replies, and
576 those queued behind them.
577  
578 =head2 max_pending($limit)
579  
580 Get or set the maximum number of commands sent to Redis at once (0, the
581 default, means unlimited); further commands wait locally and go out as
582 replies arrive. (P)subscribe, (p)unsubscribe and monitor hold no slot.
583  
584 =head2 waiting_timeout($ms)
585  
586 Get or set the maximum time in milliseconds a command can wait locally
587 before it fails with "waiting timeout" (0, the default, means unlimited).
588 Time held only for transaction replies does not count.
589  
590 =head2 resume_waiting_on_reconnect($bool)
591  
592 Get or set the option of the same name (see C<new>).
593  
594 =head2 priority($priority)
595  
596 Get or set the priority for the underlying libev IO watchers. Higher priority
597 watchers are invoked before lower priority ones when multiple watchers are
598 pending. Valid range is -2 (lowest) to +2 (highest), with 0 being the default.
599 Values outside this range are clamped automatically.
600 Can be changed at any time, including while connected.
601  
602 $redis->priority(1); # higher priority
603 $redis->priority(-1); # lower priority
604 $redis->priority(99); # clamped to 2
605 my $prio = $redis->priority; # get current priority
606  
607 =head2 keepalive($seconds)
608  
609 Get or set the TCP keepalive interval (see C<new>). A positive value set
610 while connected over TCP applies at once, and croaks if the system refuses
611 it; 0 applies from the next connection.
612  
613 =head2 prefer_ipv4($bool)
614  
615 =head2 prefer_ipv6($bool)
616  
617 Get or set the address family preference (see C<new>); setting one to a
618 true value clears the other. Takes effect on the next connection.
619  
620 =head2 source_addr($addr)
621  
622 Get or set the local address to bind TCP connections to (C<undef> clears).
623 Takes effect on the next connection.
624  
625 =head2 tcp_user_timeout($ms)
626  
627 =head2 cloexec($bool)
628  
629 =head2 reuseaddr($bool)
630  
631 Get or set the option of the same name (see C<new>). Takes effect on the
632 next connection.
633  
634 =head2 skip_waiting
635  
636 Cancel only waiting (not yet sent) command callbacks. Each callback is invoked
637 with C<(undef, "skipped")>. In-flight commands continue normally. Commands
638 issued by those callbacks are not cancelled.
639  
640 =head2 skip_pending
641  
642 Cancel all pending and waiting command callbacks: each is invoked at once
643 with C<(undef, "skipped")>, and replies that arrive later are discarded.
644 Commands issued by those callbacks are not cancelled. On a MONITOR
645 connection the monitor stream is left running.
646  
647 =head2 can($method)
648  
649 Returns a code reference for real methods, and for Redis commands once
650 they have been called; undef otherwise.
651  
652 =head1 DESTRUCTION BEHAVIOR
653  
654 When an EV::Redis object is destroyed with commands still pending or
655 waiting, their callbacks get C<"disconnected"> (pending ones get the
656 connection error, if one is in flight). An object still alive at global
657 destruction (a package variable, or one kept by a reference cycle) runs no callbacks.
658  
659 B<Circular references:> callbacks that close over C<$redis> form a cycle
660 that keeps the object alive. Break it by clearing the handlers:
661  
662 $redis->on_error(undef);
663 $redis->on_connect(undef);
664 $redis->on_disconnect(undef);
665 $redis->on_push(undef);
666  
667 =head1 BENCHMARKS
668  
669 Measured on Linux with Unix socket connection, 100,000 commands with
670 100-byte values, Perl 5.40, Redis 8.x (C<bench/benchmark.pl> in the source
671 repository, C<BENCH_COMMANDS=100000>):
672  
673 Pipeline SET ~107K ops/sec
674 Pipeline GET ~112K ops/sec
675 Mixed workload ~112K ops/sec
676 Fire-and-forget SET ~655K ops/sec
677 Sequential round-trip ~39K ops/sec (SET+GET pairs)
678  
679 Fire-and-forget mode (no callback) is roughly 6x faster than callback mode
680 due to zero Perl-side overhead per command. Pipeline throughput is bounded
681 by the event loop round-trip, not by hiredis or the network.
682  
683 Flow control (C<max_pending>) has minimal impact at reasonable limits:
684  
685 unlimited ~180K ops/sec
686 max_pending=500 ~186K ops/sec
687 max_pending=100 ~146K ops/sec
688  
689 Run C<perl bench/benchmark.pl> in a checkout of the repository for full
690 results. Set C<BENCH_COMMANDS> and C<BENCH_VALUE_SIZE> environment variables
691 to customize; the default of 10,000 commands gives different rates.
692  
693 =head1 AUTHOR
694  
695 Daisuke Murase (typester) (original L<EV::Hiredis>)
696  
697 vividsnow
698  
699 =head1 COPYRIGHT AND LICENSE
700  
701 Copyright (c) 2013 Daisuke Murase, 2026 vividsnow. All rights reserved.
702  
703 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
704  
705 =cut
↑ Summary deps/hiredis/alloc.h »