++ed by:
HARRYL BEROV

2 PAUSE users
1 non-PAUSE user.

Svetoslav Naydenov

NAME

Mojo::MySQL5::PubSub - Publish/Subscribe

SYNOPSIS

  use Mojo::MySQL5::PubSub;

  my $pubsub = Mojo::MySQL5::PubSub->new(mysql => $mysql);
  my $cb = $pubsub->listen(foo => sub {
    my ($pubsub, $payload) = @_;
    say "Received: $payload";
  });
  $pubsub->notify(foo => 'bar');
  $pubsub->unlisten(foo => $cb);

DESCRIPTION

Mojo::MySQL5::PubSub is implementation of the publish/subscribe pattern used by Mojo::MySQL5.

Although MySQL does not have SUBSCRIBE/NOTIFY like PostgreSQL and other RDBMs, this module implements similar feature.

Single Database connection waits for notification by executing SLEEP on server. connection_id and subscribed channels in stored in mojo_pubsub_subscribe table. Inserting new row in mojo_pubsub_notify table triggers KILL QUERY for all connections waiting for notification.

PROCESS privilege is needed for MySQL user to see other users processes. SUPER privilege is needed to be able to execute KILL QUERY for statements started by other users. SUPER privilege may be needed to be able to define trigger.

If your applications use this module using different MySQL users it is important the migration script to be executed by user having SUPER privilege on the database.

EVENTS

Mojo::MySQL5::PubSub inherits all events from Mojo::EventEmitter and can emit the following new ones.

reconnect

  $pubsub->on(reconnect => sub {
    my ($pubsub, $db) = @_;
    ...
  });

Emitted after switching to a new database connection for sending and receiving notifications.

ATTRIBUTES

Mojo::MySQL5::PubSub implements the following attributes.

mysql

  my $mysql = $pubsub->mysql;
  $pubsub   = $pubsub->mysql(Mojo::MySQL5->new);

Mojo::MySQL5 object this publish/subscribe container belongs to.

METHODS

Mojo::MySQL5::PubSub inherits all methods from Mojo::EventEmitter and implements the following new ones.

listen

  my $cb = $pubsub->listen(foo => sub {...});

Subscribe to a channel, there is no limit on how many subscribers a channel can have.

  # Subscribe to the same channel twice
  $pubsub->listen(foo => sub {
    my ($pubsub, $payload) = @_;
    say "One: $payload";
  });
  $pubsub->listen(foo => sub {
    my ($pubsub, $payload) = @_;
    say "Two: $payload";
  });

notify

  $pubsub = $pubsub->notify('foo');
  $pubsub = $pubsub->notify(foo => 'bar');

Notify a channel.

unlisten

  $pubsub = $pubsub->unlisten(foo => $cb);

Unsubscribe from a channel.

DEBUGGING

You can set the MOJO_PUBSUB_DEBUG environment variable to get some advanced diagnostics information printed to STDERR.

  MOJO_PUBSUB_DEBUG=1

SEE ALSO

Mojo::MySQL5, Mojolicious::Guides, http://mojolicio.us.