You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elixir Supervisor的supervise与worker函数弃用问题解决

解决Elixir Supervisor.Spec相关弃用警告的代码示例

阅读旧教程《Working with Supervisors in Elixir | Culttt》时,代码可正常运行,但启动Supervisor时出现Supervisor.Spec.supervise/2和worker/2的弃用警告。参考Elixir 1.13的Supervisor文档修改代码时遇到报错,以下是消除警告的正确代码示例:

原代码

defmodule Flakey.Service do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def init(:ok) do
    {:ok, :ok}
  end

  def check do
    GenServer.call(__MODULE__, {:check})
  end

  def handle_call({:check}, _from, :ok) do
    {:reply, :ok, :ok}
  end
end

defmodule Flakey.Supervisor do
  use Supervisor

  def start_link do
    Supervisor.start_link(__MODULE__, [])
  end

  def init(_) do
    children = [
      worker(Flakey.Service, [])
    ]

    supervise(children, strategy: :one_for_one)
  end
end

警告信息

Compiling 1 file (.ex)
warning: Supervisor.Spec.supervise/2 is deprecated. Use the new child specifications outlined in the Supervisor module instead
 lib/flakey.ex:34: Flakey.Supervisor.init/1
warning: Supervisor.Spec.worker/2 is deprecated. Use the new child specifications outlined in the Supervisor module instead
 lib/flakey.ex:31: Flakey.Supervisor.init/1

更新后的可用代码

defmodule Flakey.Service do
  use GenServer

  def start_link([])do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def init(:ok) do
    {:ok, :ok}
  end

  def check do
    GenServer.call(__MODULE__, {:check})
  end

  def handle_call({:check}, _from, :ok) do
    {:reply, :ok, :ok}
  end
end

defmodule Flakey.Supervisor do
  use Supervisor

  def start_link do
    Supervisor.start_link(__MODULE__, [])
  end

  def init(_) do
    children = [
      {Flakey.Service, []}
    ]

    Supervisor.init(children, strategy: :one_for_one)
  end
end

内容的提问来源于stack exchange,提问作者William

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:55:15