A via tuple connects an OTP process name to a custom process registry. Instead of passing a PID, GenServer can register, locate, call, or cast to a process through the registry module. section 9.1.3
A via tuple has three elements and delegates registry-specific behavior:
- {:via, registry_module, registry_data} identifies the registry and supplies lookup data. section 9.1.3
- Registry uses {registry_name, process_key}; the key must identify the process for registration and lookup. section 9.1.3
- GenServer.start_link, GenServer.call, and GenServer.cast accept the tuple where a registered process name is expected. section 9.1.3
Registry-backed EchoServer
Define via_tuple/1 once, then start and call servers by identifiers such as "server one". The registry resolves each identifier to its process. section 9.1.3
defmodule EchoServer do
use GenServer
def start_link(id) do
GenServer.start_link(__MODULE__, nil, name: via_tuple(id)) #1
end
def init(_), do: {:ok, nil}
def call(id, some_request) do
GenServer.call(via_tuple(id), some_request) #2
end
defp via_tuple(id) do
{:via, Registry, {:my_registry, {__MODULE__, id}}} #3
end
def handle_call(some_request, _, state) do
{:reply, some_request, state}
end
end
Shows the complete helper-based pattern for registering and calling a GenServer through Registry. section 9.1.3
