« blib/lib/Lemonldap/NG/Common/Apache/Session/Store.pm
↑ Summary
blib/lib/Lemonldap/NG/Common/PSGI/Request.pm »
| 1 | package Lemonldap::NG::Common::MessageBroker::Redis; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use JSON; | ||
| 5 | |||
| 6 | our $VERSION = '2.23.0'; | ||
| 7 | our $REDISCLASS = 'Redis::Fast'; | ||
| 8 | |||
| 9 | sub new { | ||
| 10 | my ( $class, $conf, $logger ) = @_; | ||
| 11 | my $self = bless { logger => $logger }, $class; | ||
| 12 | eval { require Redis::Fast }; | ||
| 13 | if ($@) { | ||
| 14 | print STDERR "Redis::Fast not available, switching to Redis\n"; | ||
| 15 | $REDISCLASS = 'Redis'; | ||
| 16 | require Redis; | ||
| 17 | } | ||
| 18 | my $args = $conf->{messageBrokerOptions} // {}; | ||
| 19 | |||
| 20 | # Reconnection parameters | ||
| 21 | # - try to reconnect every 1s up to 3600s | ||
| 22 | $args->{reconnect} //= 3600; | ||
| 23 | $args->{every} //= 1000000; | ||
| 24 | $self->{redis} = $REDISCLASS->new(%$args); | ||
| 25 | $self->{messages} = {}; | ||
| 26 | return $self; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub publish { | ||
| 30 | my ( $self, $channel, $msg ) = @_; | ||
| 31 | die 'Not a hash msg' unless ref $msg eq 'HASH'; | ||
| 32 | my $j = eval { JSON::to_json($msg) }; | ||
| 33 | die "MessageBroker publish only hashes! $@" if $@; | ||
| 34 | $self->{redis}->publish( $channel, $j ); | ||
| 35 | } | ||
| 36 | |||
| 37 | sub subscribe { | ||
| 38 | my ( $self, $channel ) = @_; | ||
| 39 | $self->{messages}{$channel} = []; | ||
| 40 | $self->{redis}->subscribe( | ||
| 41 | $channel, | ||
| 42 | sub { | ||
| 43 | my $tmp = eval { JSON::from_json( $_[0] ) }; | ||
| 44 | if ($@) { | ||
| 45 | $self->{logger}->error("Bad message from Redis: $@"); | ||
| 46 | } | ||
| 47 | else { | ||
| 48 | push @{ $self->{messages}{$channel} }, $tmp; | ||
| 49 | } | ||
| 50 | } | ||
| 51 | ); | ||
| 52 | } | ||
| 53 | |||
| 54 | sub getNextMessage { | ||
| 55 | my ( $self, $channel, $delay ) = @_; | ||
| 56 | return undef | ||
| 57 | unless $self->{messages}{$channel}; | ||
| 58 | return shift( @{ $self->{messages}{$channel} } ) | ||
| 59 | if @{ $self->{messages}{$channel} }; | ||
| 60 | $self->{redis}->wait_for_messages( $delay || 0.001 ); | ||
| 61 | return shift( @{ $self->{messages}{$channel} } ) | ||
| 62 | if @{ $self->{messages}{$channel} }; | ||
| 63 | return; | ||
| 64 | } | ||
| 65 | |||
| 66 | sub waitForNextMessage { | ||
| 67 | my ( $self, $channel ) = @_; | ||
| 68 | return undef | ||
| 69 | unless $self->{messages}{$channel}; | ||
| 70 | |||
| 71 | # Infinite loop until one message is seen | ||
| 72 | $self->{redis}->wait_for_messages(1) | ||
| 73 | while ( !@{ $self->{messages}{$channel} } ); | ||
| 74 | return shift( @{ $self->{messages}{$channel} } ); | ||
| 75 | } | ||
| 76 | |||
| 77 | 1; |