GenServer 동작 구현
`GenServer` 동작을 익혀 요청을 비동기적으로 처리하는 견고한 상태 유지 서버 프로세스를 구축합니다.
GenServer 동작 구현은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Meet the GenServer
Welcome to GenServer, a core building block in Elixir for creating robust, stateful processes!
You've learned about basic Elixir processes and message passing. GenServer is a special type of process that provides a standardized way to manage state and handle requests, making concurrent programming much easier.
It's part of Elixir's OTP (Open Telecom Platform) behaviors, offering fault tolerance and a clear structure for your server-like processes.
Why Use GenServer?
Using a GenServer offers several key advantages:
- Standardized API: It provides a consistent interface for interacting with processes.
- State Management: It simplifies holding and updating data over time within a process.
- Fault Tolerance: When used with supervisors (covered later!), GenServers can be automatically restarted if they crash.
- Concurrency: It allows multiple clients to interact with a single process safely.
Think of it as a reliable, single-threaded server for your data or operations.
Starting a GenServer: init/1
Every GenServer begins its life by calling GenServer.start_link/3, which then invokes its init/1 callback function. This is where you set up the initial state of your server.
Let's see a basic example:
defmodule MyGenServer do
use GenServer
# Client API: How others interact with our GenServer
def start_link(initial_state) do
GenServer.start_link(__MODULE__, initial_state, name: __MODULE__)
end
# Server Callbacks: What the GenServer does internally
@impl true
def init(initial_state) do
IO.puts "[GenServer] Initializing with: #{inspect initial_state}"
{:ok, initial_state} # Return {:ok, state} to indicate success
end
end
# --- Main execution block for runnable example ---
# Start the GenServer with 'Hello Elixir!' as its initial state
{:ok, pid} = MyGenServer.start_link("Hello Elixir!")
IO.puts "[Main] GenServer started with PID: #{inspect pid}"
# For a simple script, we just start it. In a real app,
# it would be supervised and run in the background.Getting Replies: handle_call
When you need to send a request to a GenServer and wait for a reply, you use GenServer.call/2. The GenServer handles this with the handle_call/3 callback.
This is a synchronous operation: your code waits until the GenServer processes the request and sends back a response.
defmodule MyGenServer do
use GenServer
# Client API
def start_link(initial_state) do
GenServer.start_link(__MODULE__, initial_state, name: __MODULE__)
end
def get_state do
GenServer.call(__MODULE__, :get_state)
end
# Server Callbacks
@impl true
def init(initial_state) do
{:ok, initial_state}
end
@impl true
def handle_call(:get_state, _from, current_state) do
IO.puts "[GenServer] Handling :get_state call."
# {:reply, response_to_client, new_server_state}
{:reply, current_state, current_state}
end
end
# --- Main execution block ---
MyGenServer.start_link("Initial Data")
state = MyGenServer.get_state()
IO.puts "[Main] Received state from GenServer: #{inspect state}"Fire & Forget: handle_cast
Sometimes you just want to send a message to a GenServer without waiting for a reply. This is where GenServer.cast/2 comes in handy, handled by the handle_cast/2 callback.
This is an asynchronous operation: your code sends the message and immediately continues, without waiting for the GenServer to process it.
defmodule MyGenServer do
use GenServer
# Client API
def start_link(initial_state) do
GenServer.start_link(__MODULE__, initial_state, name: __MODULE__)
end
def get_state do
GenServer.call(__MODULE__, :get_state)
end
def set_state(new_state) do
GenServer.cast(__MODULE__, {:set_state, new_state})
end
# Server Callbacks
@impl true
def init(initial_state) do
{:ok, initial_state}
end
@impl true
def handle_call(:get_state, _from, current_state) do
{:reply, current_state, current_state}
end
@impl true
def handle_cast({:set_state, new_state}, _current_state) do
IO.puts "[GenServer] Handling {:set_state, ...} cast."
# {:noreply, new_server_state}
{:noreply, new_state}
end
end
# --- Main execution block ---
MyGenServer.start_link("Initial Data")
IO.puts "[Main] Current state: #{MyGenServer.get_state()}"
MyGenServer.set_state("Updated Data")
Process.sleep(10) # Give cast a moment to process
IO.puts "[Main] New state after cast: #{MyGenServer.get_state()}"GenServer's Internal State
The 'state' of a GenServer is just an Elixir term (like a number, map, or list) that is passed around between its callback functions.
init/1returns the initial state.handle_call/3returns the current state as its third element.handle_cast/2returns the current state as its second element.
Each callback receives the current state as an argument and returns the new state. This simple mechanism allows your GenServer to maintain and update its internal data reliably.
Practical Example: A Counter
Let's put handle_call and handle_cast together to build a simple counter GenServer. It will allow us to increment the counter (async) and get its current value (sync).
defmodule Counter do
use GenServer
# Client API
def start_link do
GenServer.start_link(__MODULE__, 0, name: __MODULE__)
end
def increment do
GenServer.cast(__MODULE__, :increment)
end
def get_count do
GenServer.call(__MODULE__, :get_count)
end
# Server Callbacks
@impl true
def init(initial_count) do
IO.puts "[Counter] Initialized to: #{initial_count}"
{:ok, initial_count}
end
@impl true
def handle_cast(:increment, current_count) do
new_count = current_count + 1
IO.puts "[Counter] Incremented to: #{new_count}"
{:noreply, new_count}
end
@impl true
def handle_call(:get_count, _from, current_count) do
IO.puts "[Counter] Returning current count: #{current_count}"
{:reply, current_count, current_count}
end
end
# --- Main execution block ---
Counter.start_link()
IO.puts "[Main] Initial count: #{Counter.get_count()}"
Counter.increment()
Counter.increment()
Process.sleep(10) # Give casts time to process
IO.puts "[Main] Count after increments: #{Counter.get_count()}"Beyond Call & Cast
While handle_call and handle_cast are the most common, GenServers have other callbacks:
handle_info/2: For handling general messages sent directly to the process (e.g., usingsend/2).terminate/2: For cleanup code when the GenServer is about to stop.code_change/3: For handling hot code upgrades without stopping the server.
These callbacks provide even more control over the GenServer's lifecycle and behavior.
GenServer Best Practices
To make your GenServers effective and maintainable, consider these tips:
- Separate Client API: Keep the
start_link,call, andcastfunctions separate from the@implcallbacks. - Small State: Try to keep the GenServer's internal state minimal and simple.
- Avoid Long Operations: Don't perform time-consuming tasks directly in callbacks; this can block other requests. Use Elixir's
Taskmodule for such work. - Use Names: Register your GenServers with names (e.g.,
name: __MODULE__) for easy lookup across your application.
GenServer Check-up
Time for a quick question to check your understanding of GenServers!
GenServer: Key Takeaways
You've mastered the fundamentals of GenServer behavior!
- GenServers are stateful processes that manage data and handle requests.
init/1sets up the initial state.GenServer.call/2(handled byhandle_call/3) is for synchronous requests that expect a reply.GenServer.cast/2(handled byhandle_cast/2) is for asynchronous, 'fire-and-forget' messages.- The GenServer's state is passed between callbacks, allowing it to evolve over time.
GenServers are a powerful tool for building concurrent and fault-tolerant applications in Elixir.
자주 묻는 질문
“GenServer 동작 구현” 강의는 무료인가요?
네 — “GenServer 동작 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“GenServer 동작 구현”에서 뭘 배우나요?
`GenServer` 동작을 익혀 요청을 비동기적으로 처리하는 견고한 상태 유지 서버 프로세스를 구축합니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“GenServer 동작 구현” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Elixir 프로세스와 메시지 전달
- GenServer 동작 구현
- 감독자와 애플리케이션 구조
- Task와 Agent를 사용한 동시 작업