0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · 课时

实现 GenServer 行为

学习实现 GenServer,管理状态并处理同步和异步调用,构成大多数 Erlang 组件的基础。

实现 GenServer 行为 是 CoddyKit 上的免费 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is a GenServer?

Welcome back! In the previous lesson, we learned about Erlang's OTP behaviors. One of the most important is the GenServer.

  • A GenServer is a generic server that handles requests.
  • It manages internal state and processes messages in a sequential manner.
  • Think of it as a standardized way to build reliable, fault-tolerant server processes in Erlang.

It's the foundation for many Erlang applications.

GenServer's Core: Callbacks

To implement a GenServer, you define a module that exports specific callback functions. These functions are called by the gen_server behavior at different stages.

  • init/1: Initializes the server's state.
  • handle_call/3: Handles synchronous client requests (expects a reply).
  • handle_cast/2: Handles asynchronous client requests (fire-and-forget).
  • terminate/2: Cleans up when the server stops.
  • code_change/3: Handles hot code upgrades.

We'll focus on init, handle_call, and handle_cast in this lesson.

Initializing State with `init/1`

Every GenServer starts by initializing its state. This is done in the init/1 callback function.

It takes one argument (typically a list of arguments passed during startup) and should return {ok, State}, where State is the initial data your GenServer will manage.

Here's a basic init function:

-module(my_counter).
-behaviour(gen_server).
-export([init/1]).

init([]) ->
    io:format("Counter initialized with state 0.~n"),
    {ok, 0}.

Starting a GenServer Process

To get our GenServer running, we need to start it. The common way is using gen_server:start_link/3 or gen_server:start_link/4. We'll add a start_link/0 function to our module.

The start_link function creates a new Erlang process and links it to the calling process, making it part of a supervision tree (more on this later!).

-module(my_counter).
-behaviour(gen_server).
-export([start_link/0, init/1]).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

init([]) ->
    io:format("Counter process started!~n"),
    {ok, 0}.

Synchronous Calls: `handle_call`

When a client needs a reply from the server, it makes a synchronous call using gen_server:call/2 or gen_server:call/3.

The GenServer handles these requests in its handle_call/3 callback. This function takes three arguments:

  • Request: The message from the client.
  • From: The sender's process ID (Pid) and a tag.
  • State: The current internal state of the GenServer.

It typically returns {reply, Reply, NewState}.

Implementing `handle_call` (Counter)

Let's add an increment function to our counter. This will be a synchronous call, meaning the client waits for the new count.

Try running this code. First, compile it (`c(my_counter).`), then start it (`my_counter:start_link().`). You can then call `my_counter:increment().` to see the counter increase.

-module(my_counter).
-behaviour(gen_server).
-export([start_link/0, increment/0, get_count/0]).
-export([init/1, handle_call/3, handle_cast/2, terminate/2, code_change/3]).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

increment() ->
    gen_server:call(?MODULE, increment).

get_count() ->
    gen_server:call(?MODULE, get_count).

init([]) ->
    {ok, 0}.

handle_call(increment, _From, State) ->
    NewState = State + 1,
    {reply, NewState, NewState};
handle_call(get_count, _From, State) ->
    {reply, State, State};
handle_call(_Request, _From, State) ->
    {reply, {error, bad_request}, State}.

handle_cast(_Msg, State) -> % Placeholder
    {noreply, State}.

terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.

Asynchronous Calls: `handle_cast`

Sometimes, a client doesn't need a reply and just wants to send a message without waiting. This is an asynchronous call using gen_server:cast/2.

The GenServer handles these messages in its handle_cast/2 callback. It takes two arguments:

  • Message: The message from the client.
  • State: The current internal state of the GenServer.

It always returns {noreply, NewState} because no reply is sent back to the client.

Implementing `handle_cast` (Reset)

Let's add a reset function to our counter. This will be an asynchronous call, as the client doesn't need to know the new count immediately.

Compile and start the module as before. Call `my_counter:increment().` a few times, then `my_counter:reset().`. You'll notice `reset` returns immediately without a value.

-module(my_counter).
-behaviour(gen_server).
-export([start_link/0, increment/0, get_count/0, reset/0]).
-export([init/1, handle_call/3, handle_cast/2, terminate/2, code_change/3]).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

increment() ->
    gen_server:call(?MODULE, increment).

get_count() ->
    gen_server:call(?MODULE, get_count).

reset() ->
    gen_server:cast(?MODULE, reset).

init([]) ->
    {ok, 0}.

handle_call(increment, _From, State) ->
    NewState = State + 1,
    {reply, NewState, NewState};
handle_call(get_count, _From, State) ->
    {reply, State, State};
handle_call(_Request, _From, State) ->
    {reply, {error, bad_request}, State}.

handle_cast(reset, _State) ->
    {noreply, 0};
handle_cast(_Msg, State) ->
    {noreply, State}.

terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.

GenServer State Management

The power of GenServers lies in how they manage state. The State argument is passed into each callback, and the callback returns a NewState.

  • This ensures that only one process (the GenServer itself) ever modifies its state, preventing race conditions.
  • It makes the server's internal logic easier to reason about.
  • The state can be any Erlang term: an integer, a list, a map, a record, or a complex data structure.

This sequential processing of messages and explicit state passing is key to Erlang's concurrency model.

GenServer Call Types

Which of the following statements about GenServer calls are TRUE?

Recap: Implementing GenServer

You've successfully built your first GenServer! Here's what we covered:

  • GenServers are standard OTP behaviors for building stateful servers.
  • The init/1 callback initializes the server's state.
  • gen_server:start_link creates the GenServer process.
  • handle_call/3 handles synchronous requests (client waits for reply).
  • handle_cast/2 handles asynchronous messages (client doesn't wait).
  • GenServers manage their state by passing it between callbacks, ensuring sequential updates.

Next, we'll see how supervisors can automatically restart failed GenServers!

常见问题解答

「实现 GenServer 行为」课时是免费的吗?

是的 — 「实现 GenServer 行为」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程共包含 4 节课。

「实现 GenServer 行为」这节课中我会学到什么?

学习实现 GenServer,管理状态并处理同步和异步调用,构成大多数 Erlang 组件的基础。 你通过在浏览器中直接运行的动手代码来练习 Erlang OTP: Distributed & Fault-Tolerant Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「实现 GenServer 行为」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课中编写并运行代码吗?

能。每节 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 理解 OTP 与行为
  2. 实现 GenServer 行为
  3. 监管者入门
  4. 构建 OTP 应用与发布包
← 返回 Erlang OTP: Distributed & Fault-Tolerant Systems Programming