In GenServer.start_link/3 I can register a name locally using an atom for a process like this:
defmodule Worker do
use GenServer
def start_link do
GenServer.start_link(__MODULE__, nil, name: :worker)
end
end
Then I can start a supervisor to supervise this process:
defmodule Boss do
use Supervisor
def init(_) do
children = [worker(Worker, [])]
supervise(children, strategy: :one_for_one)
end
end
Now I want to make the supervisor to supervise 3 Worker processes, so I need to give those 3 processes unique names, so that when supervisor restarts the process it will always use the same symbolic name.
I can simply use string interpolation for the unique Worker process name like this:
defmodule Worker do
use GenServer
def start_link(id) do
GenServer.start_link(__MODULE__, nil, name: :"worker_#{id}")
end
end
Then supervise 3 processes like this:
defmodule Boss do
use Supervisor
def init(_) do
children = for id <- 1..3 do
worker(Worker, [id], id: id)
end
supervise(children, strategy: :one_for_one)
end
end
It works like expected.
In the doc for GenServer under "Name registration" section, it says you can use {:via, module, term} to register a name as well.
{:via, module, term}- the GenServer is registered with the given mechanism and name. The:viaoption expects a module that exportsregister_name/2,unregister_name/1,whereis_name/1, andsend/2. One such example is the:globalmodule which uses these functions for keeping the list of names of processes and their associated PIDs that are available globally for a network of Elixir nodes. Elixir also ships with a local, decentralized and scalable registry called Registry for locally storing names that are generated dynamically.
However, in order to use :via option you have to implement a module that exports register_name/2, unregister_name/1, whereis_name/1 and send/2, which seems pretty cumbersome comparing to simply use string interpolation technique as shown above.
So my question is:
- What's the benefit of registering name using {:via, module, term} over simply using string interpolation?
- Is there a pragmatic example of using
:viaoption to register name?