gpt4 book ai didi

elixir - 子进程可以访问单个应用程序范围的进程

转载 作者:行者123 更新时间:2023-12-02 05:57:27 25 4
gpt4 key购买 nike

我正在编写一个 Elixir 应用程序,其中一些访问数据库的进程将为插入的记录生成唯一标识符。

我正在使用CUID library这将让我通过以下方式生成一个 id:

{:ok, pid} = Cuid.start_link
Cuid.generate(pid) # => ch72gsb320000udocl363eofy

这是我的应用程序的设置方式

  • 有一个phoenix Controller 来处理请求
  • 此 Controller 调用我的自定义 Repo.insert 命令,该命令当前是同步的
  • Repo.insert 每次都会调用 Cuid.start_link 和 Cuid.generate

每次创建一个新的 Cuid 进程对我来说都是错误的,特别是考虑到 Cuid 库在其状态下维护一个计数器。

我的应用程序中的不同进程如何将 Cuid.generate 发送到同一进程?

谢谢!

最佳答案

您可以在应用程序中将其作为受监督和注册的工作人员启动:

defmodule MyApp do
use Application

def start(_type, _args) do
import Supervisor.Spec, warn: false

children = [
# Start the endpoint when the application starts
supervisor(MyApp.Endpoint, []),
# Start the Ecto repository
worker(MyApp.Repo, []),
worker(Cuid, [], [name: :cuid])
]

opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end

...
end

然后在您的应用程序中使用它,例如:

cuid = Cuid.generate(:cuid)

关于elixir - 子进程可以访问单个应用程序范围的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36087215/

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