elixir之使用 :simple_one_for_one strategy 时的子参数
当使用 :simple_one_for_one
策略时,我们指定子项动态启动:
supervise([worker(FooServer, [])], strategy: :simple_one_for_one)
然后我们使用类似下面的东西来启动 child :
def start_child(arg1, arg2) do
Supervisor.start_child(__MODULE__, [arg1, arg2])
end
documentation状态(强调我的):
In the case of :simple_one_for_one, the child specification defined in the supervisor will be used and instead of a child_spec, an arbitrary list of terms is expected. The child process will then be started by appending the given list to the existing function arguments in the child specification.
我尝试了以下方法
supervise([worker(FooServer, [:foo])], strategy: :simple_one_for_one)
# ^^^^
# "fixed" argument
但似乎没有附加参数,我找不到如何访问这些固定参数。甚至可以这样做吗?
请您参考如下方法:
我在iex中使用了如下代码:
defmodule Child do
def start_link(arg, arg2) do
IO.inspect(arg)
IO.inspect(arg2)
pid = spawn fn() ->
receive do
_any -> arg
end
end
{:ok, pid}
end
end
defmodule Sup do
use Supervisor
def start_link do
Supervisor.start_link(__MODULE__, [], name: __MODULE__)
end
def init(_args) do
children = [
worker(Child, [:arg], restart: :transient)
]
supervise(children, strategy: :simple_one_for_one)
end
def start_child do
Supervisor.start_child(__MODULE__, [:arg2])
end
end
这是我得到的行为:
iex(1)> Supervisor.start_link
{:ok, #PID<xxxxx>}
iex(2)> Supervisor.start_child
:arg
:arg2
{:ok, #PID<0.69.0>}
所以看起来它对我来说工作正常。在无法查看代码的情况下,很难就代码中发生的事情提供建议,但也许您的期望是您的参数是一个参数列表,而实际上您是将每个参数作为单独的参数接收。
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。