OTP Multiple Supervised Agent Workers
How to have multiple supervised agent processes of the same type in Elixir.
in the agent module:
def worker_spec(name) do
id = "#{__MODULE__}.#{String.capitalize(name)}" |> String.to_atom()
Supervisor.child_spec({__MODULE__, name: id}, id: id)
end
Important is line 2. This function can dynamically create specs for the
supervisor by overriding the :id
property. This way, you can have the same
module/agent supervised multiple times.
Then use the agent in it's supervisor module:
def init(_opts) do
children = [
MyModule.worker_spec("first"),
MyModule.worker_spec("second")
]
Supervisor.init(children, strategy: :one_for_one)
end
Important is line 3. This function can dynamically create specs for the supervisor by overriding the :id
property. This way, you can have the same module/agent supervised multiple times.