gpt4 book ai didi

elixir - 使用持久状态更正 GenServer 实现

转载 作者:行者123 更新时间:2023-12-04 08:39:12 26 4
gpt4 key购买 nike

我对一些 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

我在这里错过了什么?

最佳答案

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

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

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

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

关于elixir - 使用持久状态更正 GenServer 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64648099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com