Using Phoenix.PubSub as a message-bus for Elixir cluster

RMAG news

In my sharing session about using Phoenix.PubSub as message-bus for Elixir cluster, it quite simple and effective way for small & medium system. Now I recap it.

For standalone Elixir app (without Phoenix framework), we need add depend libraries to mix file:

defp deps do
[
{:phoenix_pubsub, “~> 2.1”},
{:libcluster, “~> 3.3”}
]
end

:phoenix_pubsub is a library from Phoenix framework, it can run without framework.
:libcluster is a new way to run Elixir app in cluster by declare config in config.exs

config :libcluster,
topologies: [
local_epmd: [
# The selected clustering strategy. Required.
strategy: Cluster.Strategy.LocalEpmd,
# Configuration for the provided strategy. Optional.
config: [hosts: [:”frontend_1@127.0.0.1″, :”front_end_2@127.0.0.1″, :”trading@127.0.0.1″]],
# The function to use for connecting nodes. The node
# name will be appended to the argument list. Optional
connect: {:net_kernel, :connect_node, []},
# The function to use for disconnecting nodes. The node
# name will be appended to the argument list. Optional
disconnect: {:erlang, :disconnect_node, []},
# The function to use for listing nodes.
# This function must return a list of node names. Optional
list_nodes: {:erlang, :nodes, [:connected]},
]]

This is simple config for run cluster by :libcluster

In Phoenix app just add :libcluster & its config are enough.

Add Application module in app need to use PubSub we need to add a child process to application supervisor (or your supervisor)

children = [
{Phoenix.PubSub, name: Trading.PubSub},

]

In process need to receive message from message-bus we need to run subscribe to subscribe a topic on a PubSub like:

PubSub.subscribe(pubsub_name, topic_name)

pubsub_name is name of PubSub we create in supervisor.
topic_name is name of topic in PubSub we want
to receive messages.

After done with PubSub we need to unsubscribe to remove process out of PubSub (in case we don’t run PubSub will send to unknown process then Erlang VM will drop it).

If want to send message to bus we need to use broadcast function to send messages:

PubSub.broadcast(pubsub_name, topic, {:join, my_id, “Hello”})

{:join, my_id, “Hello”} is our message.

Now, we can send message around cluster with a little effort.

Conclusion
:libcluster help us join apps to cluster just by add config.
:phoenix_pubsub help us send message cross cluster.

Source available at our Github repo

Please follow and like us:
Pin Share