المشرفون الديناميكيون وRegistry
تعلّموا بدء العمليات وإيقافها ديناميكيًا باستخدام `DynamicSupervisor`، واستخدموا `Registry` للبحث عن العمليات.
المشرفون الديناميكيون وRegistry درس مجاني في Elixir & Phoenix: Scalable Backend Development على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Elixir & Phoenix: Scalable Backend Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Elixir & Phoenix: Scalable Backend Development 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Dynamic Process Management
In previous lessons, we learned about supervisors for managing a fixed set of processes. But what if your application needs to create or destroy processes on demand, like for each user session or a specific task?
This is where dynamic process management comes in handy. It allows your application to adapt and scale by creating processes only when they are needed.
Introducing DynamicSupervisor
Elixir's DynamicSupervisor is designed precisely for this purpose. Unlike Supervisor, which manages a predefined list of children, a DynamicSupervisor starts with no children.
It provides functions to dynamically add and remove child processes during runtime, giving you flexible control over your application's process tree.
Starting a DynamicSupervisor
To use a DynamicSupervisor, you first need to start it, typically within your application's supervision tree. Here's a basic setup:
defmodule MyApp.DynamicManager do
use DynamicSupervisor
def start_link(init_arg) do
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
DynamicSupervisor.init(strategy: :one_for_one)
end
end
# To run this in an IEx session:
# {:ok, pid} = MyApp.DynamicManager.start_link([])
# IO.puts("DynamicSupervisor started with PID: #{inspect(pid)}")Adding Children Dynamically
Once your DynamicSupervisor is running, you can add new children using DynamicSupervisor.start_child/2. Each child needs a child specification defining how it should be started.
Let's create a simple GenServer that the supervisor can manage.
defmodule MyApp.Worker do
use GenServer
def start_link(id) do
GenServer.start_link(__MODULE__, id, name: via_tuple(id))
end
def init(id) do
IO.puts("Worker #{id} started!")
{:ok, id}
end
defp via_tuple(id), do: {:via, Registry, {MyApp.Registry, id}}
end
defmodule MyApp.DynamicManager do
use DynamicSupervisor
def start_link(init_arg) do
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
DynamicSupervisor.init(strategy: :one_for_one)
end
def start_worker(id) do
child_spec = %{
id: id,
start: {MyApp.Worker, :start_link, [id]}
}
DynamicSupervisor.start_child(__MODULE__, child_spec)
end
end
# To run this in an IEx session:
# {:ok, manager_pid} = MyApp.DynamicManager.start_link([])
# {:ok, worker_pid} = MyApp.DynamicManager.start_worker(:user_123)
# IO.puts("Worker PID: #{inspect(worker_pid)}")Stopping Dynamic Children
Just as you can start children dynamically, you can also stop them. Use DynamicSupervisor.terminate_child/2 with the child's PID.
The supervisor will handle the graceful shutdown of the process.
defmodule MyApp.Worker do
use GenServer
def start_link(id) do
GenServer.start_link(__MODULE__, id, name: {:global, id})
end
def init(id) do
IO.puts("Worker #{id} started!")
{:ok, id}
end
def terminate(_reason, id) do
IO.puts("Worker #{id} stopping!")
end
end
defmodule MyApp.DynamicManager do
use DynamicSupervisor
def start_link(init_arg) do
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
DynamicSupervisor.init(strategy: :one_for_one)
end
def start_worker(id) do
child_spec = %{id: id, start: {MyApp.Worker, :start_link, [id]}}
DynamicSupervisor.start_child(__MODULE__, child_spec)
end
def stop_worker(worker_pid) do
DynamicSupervisor.terminate_child(__MODULE__, worker_pid)
end
end
# To run this in an IEx session:
# {:ok, manager_pid} = MyApp.DynamicManager.start_link([])
# {:ok, worker_pid} = MyApp.DynamicManager.start_worker(:task_A)
# :timer.sleep(100)
# MyApp.DynamicManager.stop_worker(worker_pid)
# :timer.sleep(100)
# IO.puts("Worker process should now be stopped.")The Need for a Registry
When you start processes dynamically, how do you find them later? If you only have their PIDs, what happens if a process crashes and restarts with a new PID?
We need a way to assign a persistent, meaningful name to a process and look it up reliably, regardless of its current PID. This is where Elixir's Registry comes in.
What is Registry?
The Registry module provides a local, distributed, and fault-tolerant key-value store for associating arbitrary terms (keys) with process identifiers (PIDs).
It's perfect for looking up processes by a name or ID, especially when dealing with dynamic processes or when you want to use a custom name instead of global or local atoms.
Starting and Using Registry
Like other OTP behaviors, Registry needs to be started, typically as part of your application's supervision tree. You can define multiple registries, each with its own scope.
Once started, you can register processes with keys and look them up.
defmodule MyApp.Registry do
use Registry, keys: :unique, name: __MODULE__
end
defmodule MyApp.WorkerWithRegistry do
use GenServer
def start_link(id) do
GenServer.start_link(__MODULE__, id, name: {:via, Registry, {MyApp.Registry, id}})
end
def init(id) do
IO.puts("Worker #{id} started and registered!")
{:ok, id}
end
def get_state(pid) do
GenServer.call(pid, :get_state)
end
@impl true
def handle_call(:get_state, _from, state) do
{:reply, state, state}
end
end
# To run this in an IEx session:
# {:ok, _} = MyApp.Registry.start_link([]) # Start the registry
# {:ok, worker_pid} = MyApp.WorkerWithRegistry.start_link(:session_1)
# IO.puts("Registered worker PID: #{inspect(worker_pid)}")
#
# {:ok, [pid_found]} = Registry.lookup(MyApp.Registry, :session_1)
# IO.puts("Looked up PID: #{inspect(pid_found)}")
# IO.puts("Worker state: #{MyApp.WorkerWithRegistry.get_state(pid_found)}")DynamicSupervisor with Registry
Combining DynamicSupervisor with Registry is a powerful pattern. You can dynamically start worker processes, and each worker registers itself with a unique key in the Registry.
This allows other parts of your application to find and interact with specific worker processes without needing their PIDs directly.
defmodule MyApp.UserSession do
use GenServer
def start_link(user_id) do
# Register with Registry using the user_id as key
GenServer.start_link(__MODULE__, user_id, name: {:via, Registry, {MyApp.SessionsRegistry, user_id}})
end
def init(user_id) do
IO.puts("Session for user #{user_id} started.")
{:ok, user_id}
end
def get_user_id(pid) do
GenServer.call(pid, :get_user_id)
end
@impl true
def handle_call(:get_user_id, _from, user_id) do
{:reply, user_id, user_id}
end
end
defmodule MyApp.SessionsRegistry do
use Registry, keys: :unique, name: __MODULE__
end
defmodule MyApp.SessionSupervisor do
use DynamicSupervisor
def start_link(init_arg) do
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
DynamicSupervisor.init(strategy: :one_for_one)
end
def start_session(user_id) do
child_spec = %{
id: user_id,
start: {MyApp.UserSession, :start_link, [user_id]}
}
DynamicSupervisor.start_child(__MODULE__, child_spec)
end
end
# --- Application Entry Point --- (Simulated)
{:ok, _registry_pid} = MyApp.SessionsRegistry.start_link([])
{:ok, _supervisor_pid} = MyApp.SessionSupervisor.start_link([])
# Start a session for user_101
{:ok, session_pid_1} = MyApp.SessionSupervisor.start_session(:user_101)
IO.puts("Session 1 PID: #{inspect(session_pid_1)}")
# Start a session for user_102
{:ok, session_pid_2} = MyApp.SessionSupervisor.start_session(:user_102)
IO.puts("Session 2 PID: #{inspect(session_pid_2)}")
# Look up user_101's session via Registry
{:ok, [pid_from_registry]} = Registry.lookup(MyApp.SessionsRegistry, :user_101)
IO.puts("Found user_101 session PID via Registry: #{inspect(pid_from_registry)}")
IO.puts("User ID from session: #{MyApp.UserSession.get_user_id(pid_from_registry)}")Dynamic & Registry Quiz
Consider an application that uses DynamicSupervisor to manage user sessions and Registry to look up sessions by user ID. What is the primary benefit of using Registry in this scenario?
Recap: Dynamic & Registry
You've mastered dynamic process management!
DynamicSupervisorallows you to start and stop child processes on demand, making your application highly flexible and adaptable.- The
Registrymodule provides a powerful key-value store for associating processes with meaningful names or IDs, enabling reliable lookup of dynamically started processes.
By combining these two, you can build robust, scalable applications that manage their resources efficiently.
الأسئلة الشائعة
هل درس «المشرفون الديناميكيون وRegistry» مجاني؟
نعم — نص درس «المشرفون الديناميكيون وRegistry» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Elixir & Phoenix: Scalable Backend Development، انتقل إلى CoddyKit PRO. تتضمن دورة Elixir & Phoenix: Scalable Backend Development 4 دروس في المجموع.
ماذا ستتعلم في «المشرفون الديناميكيون وRegistry»؟
تعلّموا بدء العمليات وإيقافها ديناميكيًا باستخدام `DynamicSupervisor`، واستخدموا `Registry` للبحث عن العمليات. تتمرن على Elixir & Phoenix: Scalable Backend Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Elixir & Phoenix: Scalable Backend Development؟
لا تُشترط خبرة سابقة. Elixir & Phoenix: Scalable Backend Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «المشرفون الديناميكيون وRegistry»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Elixir & Phoenix: Scalable Backend Development هذا؟
نعم. كل درس في Elixir & Phoenix: Scalable Backend Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- Elixir الموزّع والعنقدة
- استراتيجيات الإشراف المتقدمة
- المشرفون الديناميكيون وRegistry
- مسارات GenStage والتحكم في التدفق