通过 phoenix 通道从 redis 通道流式传输

Streaming from a redis channel through a phoenix channel

我目前正在尝试更换 with a small phoenix app. What I need to do is get information from a channel and stream it to an 客户端。我一直在尝试使用 Redis.PuSub 和 Phoenix Redis 适配器,但未能完全涵盖我们目前拥有的功能。

当前的功能是这样的:

我们的服务器接收到来自用户的请求并将一些输出记录到 Redis 通道。 该频道的名称是字符串和键的组合。 Ember 客户端然后使用相同的密钥向 action-cable 发出请求。 然后,Action-cable 从具有相同名称的 Redis 通道流式传输记录的信息。 我需要知道的是如何在用户发出请求时开始收听具有给定名称的 Redis 频道并将该信息连续流式传输到客户端。我已经设法得到一个或另一个但不是两个。

我已经为此苦思了一天多了,非常感谢任何帮助。

干杯

所以为了解决这个问题,我做了以下事情。

首先,我根据 docs 将 Redix.PubSub 设置为依赖项。然后在频道中我做了:

defmodule MyApp.ChannelName do
  use Phoenix.Channel

  def join(stream_name, _message, socket) do
    # Open a link to the redis server
    {:ok, pubsub} = Redix.PubSub.start_link()

    # Subscribe to the users stream
    Redix.PubSub.subscribe(pubsub, stream_name, self())

    {:ok, socket}
  end

  # Avoid throwing an error when a subscribed message enters the channel
  def handle_info({:redix_pubsub, redix_pid, :subscribed, _}, socket) do
    {:noreply, socket}
  end

  # Handle the message coming from the Redis PubSub channel
  def handle_info({:redix_pubsub, redix_pid, :message, %{channel: channel, payload: message}}, socket) do
    # Push the message back to the user
    push socket, "#{channel}", %{message: message}
    {:noreply, socket}
  end
end

在我的例子中,我要求用户使用某个名称注册一个频道,例如channel_my_api_key。然后我会开始监听 redis 频道 channel_my_api_key 并通过 push 函数将信息流式传输回用户。注意广播可以代替推送。

感谢来自 Elixir 论坛的 Alex Garibay,他帮助我找到了解决方案。您可以找到线程 here.