如何在phoenix elixir聊天应用程序中监控树中运行Redix并从不同模块访问

时间:2017-07-21 06:09:25

标签: redis elixir phoenix-framework elixir-framework

我想在我的聊天应用程序中使用{:redix,“〜> 0.6.1”}十六进制包并从监督树开始

{:ok, conn} = Redix.start_link()
{:ok, conn} = Redix.start_link(host: "example.com", port: 5000)
{:ok, conn} = Redix.start_link("redis://localhost:6379/3", name: :redix)


Redix.command(conn, ["SET", "mykey", "foo"])

但是当我尝试将连接开始链接放到子进程

时,它会出错
children = [
      # Start the Ecto repository
      supervisor(PhoenixChat.Repo, []),
      # Start the endpoint when the application starts
      supervisor(PhoenixChat.Endpoint, []),
      # Start your own worker by calling: PhoenixChat.Worker.start_link(arg1, arg2, arg3)
      # worker(PhoenixChat.Worker, [arg1, arg2, arg3]),
      supervisor(PhoenixChat.Presence, []),

      #supervisor(Phoenix.PubSub.Redis, [:chat_pubsub, host: "127.0.0.1"])
    ]

如何启动redix连接并将数据存储到Redis?

2 个答案:

答案 0 :(得分:5)

您要做的是Register进程ID。为此,您通常可以在opts中指定其名称,如下所示:

worker(Redix, [[], [name: RedixConnection]])

当进程注册时,通常可以使用它的名称而不是PID(总是检入文档,但这是常见模式),如下所示:

Redix.command(RedixConnection, ["PING"])

大多数情况下,一个连接是不够的。您可能希望使用某种池化机制,如poolboydocumentation中有一个非常简洁的页面供您阅读,其名称为Real-world usage。它可能会回答与此主题相关的大多数问题。

请考虑为您的事业使用Erlang / Elixir内置解决方案。我不知道您的确切用例,但您可能想查看ETS,DTS和Mnesia。

答案 1 :(得分:1)

  children = [
      # Start the Ecto repository
      supervisor(PhoenixChat.Repo, []),
      # Start the endpoint when the application starts
      supervisor(PhoenixChat.Endpoint, []),
      # Start your own worker by calling: PhoenixChat.Worker.start_link(arg1, arg2, arg3)
      # worker(PhoenixChat.Worker, [arg1, arg2, arg3]),
      supervisor(PhoenixChat.Presence, []),
      worker(Redix, [[], [name: :redix]]),

      #supervisor(Phoenix.PubSub.Redis, [:chat_pubsub, host: "127.0.0.1"])
    ]




Redix.command(:redix, ["SET", "key", "value"])