[elixir! #0009] 漫話elixir源碼之gen_server

什麼是GenServer?

defmodule GenServer do
  @moduledoc """
  A behaviour module for implementing the server of a client-server relation.
  A GenServer is a process like any other Elixir process and it can be used
  to keep state, execute code asynchronously and so on. The advantage of using
  a generic server process (GenServer) implemented using this module is that it
  will have a standard set of interface functions and include functionality for
  tracing and error reporting. It will also fit into a supervision tree.

是 generic server 的縮寫, 意爲通用服務器. 這個模塊裏包含了全部實現一個服務器所需的最基本的函數.node

GenServer的工做原理是什麼?

圖片描述

本質就是客戶端發送請求, 服務器作出相應動做.服務器

GenServer模塊中有哪些基本函數?

@callback init(args :: term) ::
    {:ok, state} |
    {:ok, state, timeout | :hibernate} |
    :ignore |
    {:stop, reason :: any} when state: any

回調函數initial/1 , 做用是肯定服務器初始化時的狀態.異步

@callback handle_call(request :: term, from, state :: term) ::
    {:reply, reply, new_state} |
    {:reply, reply, new_state, timeout | :hibernate} |
    {:noreply, new_state} |
    {:noreply, new_state, timeout | :hibernate} |
    {:stop, reason, reply, new_state} |
    {:stop, reason, new_state} when reply: term, new_state: term, reason: term

回調函數handle_call/3, 做用是處理客戶端發來的call消息.async

@callback handle_cast(request :: term, state :: term) ::
    {:noreply, new_state} |
    {:noreply, new_state, timeout | :hibernate} |
    {:stop, reason :: term, new_state} when new_state: term

回調函數handle_cast/2, 用於處理客戶端發來的cast消息.函數

@callback handle_info(msg :: :timeout | term, state :: term) ::
    {:noreply, new_state} |
    {:noreply, new_state, timeout | :hibernate} |
    {:stop, reason :: term, new_state} when new_state: term

回調函數handle_info/2, 用於處理全部其它消息(例如服務器內部信息).this

@callback terminate(reason, state :: term) ::
    term when reason: :normal | :shutdown | {:shutdown, term} | term

回調函數terminate/2, 用於關閉服務器.atom

@callback code_change(old_vsn, state :: term, extra :: term) ::
    {:ok, new_state :: term} |
    {:error, reason :: term} when old_vsn: term | {:down, term}

回調函數code_change/3, 用於對服務器上的代碼進行熱更新.spa

@spec start_link(module, any, options) :: on_start

函數start_link/3, 用於新建一個與當前進程綁定的服務器, 若當前進程終結, 服務器也會隨之關閉.hibernate

@spec start(module, any, options) :: on_start

函數start/3, 和上面的差很少, 只是沒有綁定.code

@spec stop(server, reason :: term, timeout) :: :ok

函數stop/3, 給服務器發送一箇中止消息, 附帶理由.

@spec call(server, term, timeout) :: term

函數call/3, 向服務器發送一個異步的請求, 並等待回覆.

@spec cast(server, term) :: :ok

函數cast/2, 發送一個同步的請求.

@spec abcast([node], name :: atom, term) :: :abcast

函數abcast/3, 對特定節點上的全部註冊名爲name的服務器發送cast消息.

@spec multi_call([node], name :: atom, term, timeout) ::
                  {replies :: [{node, term}], bad_nodes :: [node]}

函數multi_call/3, 對特定節點上的全部註冊名爲name的服務器發送call消息.

@spec reply(from, term) :: :ok

函數reply/2, 回覆一個客戶端.

@spec whereis(server) :: pid | {atom, node} | nil

函數whereis/1, 返回服務器進程的pid, 或服務器名稱.

相關文章
相關標籤/搜索