【问题标题】:Correct GenServer implementation with persistent state具有持久状态的正确 GenServer 实现
【发布时间】:2021-02-15 06:15:13
【问题描述】:

我对一些 OTP 概念不熟悉。我有 GenServer,它将向 RabbitMQ 发布事件。此 GenServer 的状态为:amqp Chanel,它在 init() 期间启动一次,并在 cast 调用之间持续存在。

defmodule Myapp.Events.AmqpTransport do

  require Logger
  use GenServer
  use AMQP

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

  def init(_opts) do
    username = get_conf(:username)
    password = get_conf(:password)
    host = get_conf(:host)
    port = get_conf(:port)
    vhost = String.replace(get_conf(:vhost), "/", "%2f")
    exchange = get_conf(:exchange)
    {:ok, conn} = Connection.open("amqp://#{username}:#{password}@#{host}:#{port}/#{vhost}")
    {:ok, chan} = Channel.open(conn)

    {:ok, chan}
  end

  def handle_cast({:emit, event}, chan) do
    payload = :jiffy.encode(%{event: event})
    Basic.publish(
      chan,
      get_conf(:exchange),
      get_conf(:routing_key),
      payload
    )
    {:noreply, :ok, chan}
  end

  def emit(event) do
    GenServer.cast(__MODULE__, {:emit, event})
  end

  defp get_conf(key) do
    conf = Application.get_env(:myapp_events, :rabbit)
    conf[key]
  end
end

当我使用Myapp.Events.AmqpTransport.emit(%{"hop": "hej"}) 调用它时出现错误:

[error] Supervisor 'Elixir.Myapp.Events.Supervisor' had child
        'Elixir.Myapp.Events.AmqpTransport' started with
        'Elixir.Myapp.Events.AmqpTransport':start_link([])
        at <0.7024.0> exit with reason timeout_value
        in gen_server:loop/7 line 437
        in context child_terminated

我错过了什么?

【问题讨论】:

    标签: elixir amqp erlang-otp gen-server


    【解决方案1】:

    你应该从GenDerver.handle_cast/2返回二元组{:noreply, chan},而不是三元元组{:noreply, :ok, chan}

    Cast 是异步的,因此它们不会返回任何内容。您的三元素元组 {:noreply, _, _} 被视为表单中的响应

    {:noreply, new_state,
        timeout() | :hibernate | {:continue, term()}}
    

    state,作为第三个元素传递,预计会超时(它不匹配:hibernate,也不匹配元组),但它的值无论如何都不是超时。

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 2019-08-30
      • 2015-01-17
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2020-05-10
      相关资源
      最近更新 更多