NAME

Mojo::mysql::PubSub - Publish/Subscribe

SYNOPSIS

use Mojo::mysql::PubSub;

my $pubsub = Mojo::mysql::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::mysql::PubSub is implementation of the publish/subscribe pattern used by Mojo::mysql. The implementation should be considered an EXPERIMENT and might be removed without warning!

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::mysql::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::mysql::PubSub implements the following attributes.

mysql

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

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

METHODS

Mojo::mysql::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::mysql, Mojolicious::Guides, http://mojolicio.us.