从redis频道流过凤凰频道

时间:2016-10-05 13:17:49

标签: redis elixir phoenix-framework phoenix-channels

我目前正在尝试用小凤凰应用替换。我需要做的是从频道获取信息并将其流式传输到客户端。我一直在尝试使用Redis.PuSub和Phoenix Redis适配器,但还没有完全覆盖我们目前的功能。

目前的功能如下:

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

我一直在敲打我的脑袋超过一天,所以任何帮助都会受到大力赞赏。

干杯

1 个答案:

答案 0 :(得分:3)

所以为了解决这个问题,我做了以下几点。

首先,我根据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

相关问题