我正在编写一个Elixir应用程序,其中一些访问数据库的进程将为插入的记录生成唯一标识符。
我正在使用CUID library,这会让我以下列方式生成ID:
{:ok, pid} = Cuid.start_link
Cuid.generate(pid) # => ch72gsb320000udocl363eofy
以下是我的应用设置的方式
每次创建一个新的Cuid进程对我来说都是错误的,特别是考虑到Cuid lib在其状态下维护一个计数器。
我的应用程序中的不同进程如何将Cuid.generate
发送到同一进程?
谢谢!
答案 0 :(得分:5)
您可以在应用程序中作为受监督和注册的工作人员启动它:
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)
答案 1 :(得分:2)
您可以注册您的流程:
Process.register(pid, :cuid_process)
这种方式可供整个系统中的所有进程使用。通常,您可以在所有采用常规pid的地方使用在哪个进程中注册的原子,因此您可以尝试:
Cuid.generate(:cuid_process)