1Mojo::Pg::PubSub(3) User Contributed Perl Documentation Mojo::Pg::PubSub(3)
2
3
4
6 Mojo::Pg::PubSub - Publish/Subscribe
7
9 use Mojo::Pg::PubSub;
10
11 my $pubsub = Mojo::Pg::PubSub->new(pg => $pg);
12 my $cb = $pubsub->listen(foo => sub {
13 my ($pubsub, $payload) = @_;
14 say "Received: $payload";
15 });
16 $pubsub->notify(foo => 'I ♥ Mojolicious!');
17 $pubsub->unlisten(foo => $cb);
18
20 Mojo::Pg::PubSub is a scalable implementation of the publish/subscribe
21 pattern used by Mojo::Pg. It is based on PostgreSQL notifications and
22 allows many consumers to share the same database connection, to avoid
23 many common scalability problems.
24
26 Mojo::Pg::PubSub inherits all events from Mojo::EventEmitter and can
27 emit the following new ones.
28
29 reconnect
30 $pubsub->on(reconnect => sub {
31 my ($pubsub, $db) = @_;
32 ...
33 });
34
35 Emitted after switching to a new database connection for sending and
36 receiving notifications.
37
39 Mojo::Pg::PubSub implements the following attributes.
40
41 pg
42 my $pg = $pubsub->pg;
43 $pubsub = $pubsub->pg(Mojo::Pg->new);
44
45 Mojo::Pg object this publish/subscribe container belongs to.
46
48 Mojo::Pg::PubSub inherits all methods from Mojo::EventEmitter and
49 implements the following new ones.
50
51 json
52 $pubsub = $pubsub->json('foo');
53
54 Activate automatic JSON encoding and decoding with "to_json" in
55 Mojo::JSON and "from_json" in Mojo::JSON for a channel.
56
57 # Send and receive data structures
58 $pubsub->json('foo')->listen(foo => sub {
59 my ($pubsub, $payload) = @_;
60 say $payload->{bar};
61 });
62 $pubsub->notify(foo => {bar => 'I ♥ Mojolicious!'});
63
64 listen
65 my $cb = $pubsub->listen(foo => sub {...});
66
67 Subscribe to a channel, there is no limit on how many subscribers a
68 channel can have. Automatic decoding of JSON text to Perl values can be
69 activated with "json".
70
71 # Subscribe to the same channel twice
72 $pubsub->listen(foo => sub {
73 my ($pubsub, $payload) = @_;
74 say "One: $payload";
75 });
76 $pubsub->listen(foo => sub {
77 my ($pubsub, $payload) = @_;
78 say "Two: $payload";
79 });
80
81 notify
82 $pubsub = $pubsub->notify('foo');
83 $pubsub = $pubsub->notify(foo => 'I ♥ Mojolicious!');
84 $pubsub = $pubsub->notify(foo => {bar => 'baz'});
85
86 Notify a channel. Automatic encoding of Perl values to JSON text can be
87 activated with "json".
88
89 reset
90 $pubsub->reset;
91
92 Reset all subscriptions and the database connection. This is usually
93 done after a new process has been forked, to prevent the child process
94 from stealing notifications meant for the parent process.
95
96 unlisten
97 $pubsub = $pubsub->unlisten('foo');
98 $pubsub = $pubsub->unlisten(foo => $cb);
99
100 Unsubscribe from a channel.
101
103 Mojo::Pg, Mojolicious::Guides, <https://mojolicious.org>.
104
105
106
107perl v5.28.0 2018-05-08 Mojo::Pg::PubSub(3)