mnishiguchi / kantan_cluster

Form a simple Erlang cluster easily in Elixir

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

KantanCluster

かんたんクラスター

Hex version API docs CI

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.

Getting started

Add kantan_cluster to your list of dependencies in mix.exs:

def deps do
  [
    {:kantan_cluster, "~> 0.5"}
  ]
end

Demo

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.

Configuration

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: :"node1@127.0.0.1",
  cookie: :super_secure_erlang_magic_cookie,
  topologies: [gossip_example: [
    strategy: Cluster.Strategy.Gossip,
    secret: "super_secure_gossip_secret"
  ]]

Publish-Subscribe

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

kantan_cluster_inky_experiment_20220109_175511

Acknowledgements

This project is inspired by the following:

About

Form a simple Erlang cluster easily in Elixir

License:MIT License


Languages

Language:Elixir 100.0%