Skip to content

Instantly share code, notes, and snippets.

@xiongxin
Last active September 1, 2018 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiongxin/9eb2cee3f1174b7baadc0b55487847f5 to your computer and use it in GitHub Desktop.
Save xiongxin/9eb2cee3f1174b7baadc0b55487847f5 to your computer and use it in GitHub Desktop.
GenServer使用指南

Client发送请求

def sync_op(pid, args) do
 GenServer.call(pid, {:sync_op, args})  # :sync_op 是我们指定操作的名称
end

Callback

def handle_call({:sync_op, args}, from, state) do
 new_state = f(state, args)
 {:reply, new_state}
end

回调返回值示例

{:reply, reply, new_state}
{:reply, reply, new_state, 5_000}
{:reply, reply, new_state, :hibernate}
{:noreply, new_state}
{:noreply, new_state, 5_000}
{:noreply, new_state, :hibernate}
{:stop, reason*, reply, new_state}
{:stop, reason*, new_state}

handle_cast/2 must be used for asynchronous requests, when you don’t care about a reply. A cast does not even guarantee the server has received the message and, for this reason, should be used sparingly. For example, the create/2 function we have defined in this chapter should have used call/2. We have used cast/2 for didactic purposes.

根据文档,异步操作不保证一定能发送成功,还是尽量少使用

Client发送请求

def async_op(pid, args) do
 GenServer.cast(pid, {:async_op, args})
end

Callback

def handle_cast({:async_op, args}, state) do
 new_state = f(state, args)
 {:noreply, new_state}
end

回调返回值示例

{:noreply, new_state}
{:noreply, new_state, 5_000}
{:noreply, new_state, :hibernate}
RETURN VAL
{:stop, reason*, new_state} 
def handle_info(msg, state) do
 new_state = f(state, msg)
 {:noreply, new_state}
end
{:noreply, new_state}
{:noreply, new_state, 5_000}
{:noreply, new_state, :hibernate}
RETURN VAL
{:stop, reason*, new_state} 
def stop(pid, reason \\ :normal, timeout \\ :infinity) do
 GenServer.stop(pid, reason, timeout)
end

回调函数

def terminate(reason, state) do
 # Perform cleanup here
 # …
end

reason参数的示例值

:normal
:shutdown
{:shutdown, term}
term
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment