正常退出后,应用程序无法重新启动

时间:2019-03-19 17:56:39

标签: elixir supervisor mix

我正在尝试使用tortoise连接到mqtt。当我的连接断开时,它毫无问题地接通,但是当我的应用程序退出时,它并没有根据:one_to_one策略重新启动。我在mix.exs的mod中启动了应用程序。我可以把它放在主管中然后启动主管吗?它要求无参数的start是实现此目的的正确方法。如果我的应用程序崩溃怎么办? 我的connection.ex必须是genserver吗? 请提出建议。

mix.exs

defmodule SslMqtt.MixProject do
  use Mix.Project

  def project do
    [
      app: :ssl_mqtt,
      version: "0.1.0",
      elixir: "~> 1.6",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
     mod: {SslMqtt.Application,[]}, 
     extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
    {:tortoise, "~> 0.9"}
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
    ]
  end
end

application.ex

defmodule SslMqtt.Application do
  use Application

  def start(_type, _args) do

    IO.puts "inside supervisor application start"
    SslMqtt.Supervisor.start_link(name: SslMqtt.Supervisor)
  end
end

supervisor.ex

defmodule SslMqtt.Supervisor do
  use Supervisor

  def start_link(opts) do
    IO.puts "inside supervisor start link"
    Supervisor.start_link(__MODULE__, :ok, opts)
  end

  def init(:ok) do

    IO.puts "inside supervisor init"
    children = [

  %{
        id: SslMqtt.MqttConnection,
        start: { SslMqtt.MqttConnection, :start_link, [1,2]},
        type: :worker,
        restart: :permanent,
        shutdown: 500
      }

    ]

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

connection.ex

defmodule SslMqtt.MqttConnection do

def start_link(_type,_arg) do

{:ok,pid}=Tortoise.Connection.start_link(
    client_id: William,
    server: {Tortoise.Transport.Tcp, host: 'iot.eclipse.org', port: 1883},
    handler: {Tortoise.Handler.Logger, []},
    will: %Tortoise.Package.Publish{topic: "foo/bar", payload: "goodbye"}
  )
end



end

1 个答案:

答案 0 :(得分:3)

问题出在您的Application上。应该是

def start(_type, _args) do
  children = [
    {SslMqtt.Supervisor, []}
  ]

  opts = [strategy: :one_for_one, name: SslMqtt.Supervisor]
  Supervisor.start_link(children, opts)
end

这样,应用程序将监督SslMqtt.Supervisor。您现在正在做什么,只需在不受监督的情况下开始SslMqtt.Supervisor