かんたんクラスター
Form a simple Erlang cluster easily in Elixir.
KantanCluster is a thin wrapper around libcluster and phoenix_pubsub. It allows you to try out distributed Erlang nodes easily.
Add kantan_cluster
to your list of dependencies in mix.exs
:
def deps do
[
{:kantan_cluster, "~> 0.5"}
]
end
Open an interactive Elixir shell (IEx) in a terminal, and start a node with node name and cookie.
iex
iex> Mix.install([{:kantan_cluster, "~> 0.5"}])
iex> KantanCluster.start_node(sname: :node1, cookie: :hello)
Open another terminal and do the same with a different node name. Make sure that the cookie is the same.
iex
iex> Mix.install([{:kantan_cluster, "~> 0.5"}])
iex> KantanCluster.start_node(sname: :node2, cookie: :hello)
These two nodes will be connected to each other automatically.
Alternatively, options can be loaded from your project's config/config.exs
.
For available clustering strategies, see https://hexdocs.pm/libcluster/readme.html#clustering.
config :kantan_cluster,
name: :"[email protected]",
cookie: :super_secure_erlang_magic_cookie,
topologies: [gossip_example: [
strategy: Cluster.Strategy.Gossip,
secret: "super_secure_gossip_secret"
]]
Under the hood, kantan_cluster
uses phoenix_pubsub for all the heavy-lifting.
# subscribe to hello topic in one node
iex(hoge@my-machine)> KantanCluster.subscribe("hello")
# publish a message to hello topic in another node
iex(piyo@my-machine)> KantanCluster.broadcast("hello", %{motto: "元氣があればなんでもできる"})
# check the mailbox in a node that subscribes hello topic
iex(hoge@my-machine)> flush
The messages can be handled with a GenServer
like below.
# Somebody in the cluster may publish temperature data on the topic "hello_nerves:measurements".
message = {:hello_nerves_measurements, %{temperature_c: 30.1}, node()}
KantanCluster.broadcast("hello_nerves:measurements", message)
# Anybody within the same cluster can subscribe to the topic and receive messages on the topic.
KantanCluster.subscribe("hello_nerves:measurements")
# In the subscribing process, you may receive the message using GenServer's handle_info callback.
defmodule HelloNervesSubscriber do
use GenServer
# ...
@impl GenServer
def handle_info({:hello_nerves_measurement, measurement, _node}, state) do
{:noreply, %{state | last_measurement: measurement}}
end
This project is inspired by the following:
- nerves_pack(vintage_net 含む)を使って Nerves 起動時に
Node.connect()
するようにした by nishiuchikazuma - Forming an Erlang cluster of Pi Zeros by underjord --- a great hands-on tutorial for connecting multiple Nerves devices
- Let's Talk by Herman Verschooten
- Exploring Elixir Episode 7: Effortless Scaling With Automatic Clusters
- livebook