简体   繁体   English

如何在phoenix elixir聊天应用程序的监督树中运行Redix并从其他模块访问

[英]How can I run Redix in supervision tree in phoenix elixir chat app and access from different module

I want to use {:redix, "~> 0.6.1"} hex package to my chat application and start in supervision tree 我想在我的聊天应用程序中使用{: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"])

but it gives error when I try to put connection start link to child process 但是当我尝试将连接开始链接放到子进程时却给出了错误

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"])
    ]

How can I start redix connection and store data to Redis? 如何启动Redix连接并将数据存储到Redis?

What you want to do is Register process id. 您要执行的操作是Register进程ID。 To do that you can usually specify its name in opts, like this: 为此,通常可以在opts中指定其名称,如下所示:

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

When the process is registered usually you can use it's name instead of PID (always check in documentation, but that is common pattern) like this: 通常,在注册过程后,您可以使用它的名称来代替PID(总是在文档中查阅,但这是常见的模式),如下所示:

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

Most of the time one connection isn't enough. 大多数情况下,一个连接是不够的。 You probably want to use some kind of pooling mechanism like poolboy . 您可能想要使用某种池化机制,例如poolboy There is very neat page in documentation for you to read which is called Real-world usage . 文档中有一个非常整齐的页面供您阅读,这称为“ Real-world usage It will probably answer most of the questions related to this topic. 它可能会回答与此主题相关的大多数问题。

Please also consider using Erlang/Elixir built in solutions for your cause. 也请考虑根据您的原因使用内置的Erlang / Elixir解决方案。 I don't know your exact use case but you may want to check out ETS, DTS and Mnesia. 我不知道您的确切用例,但您可能想查看ETS,DTS和Mnesia。

  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"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM