當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Elixir Registry.register用法及代碼示例

Elixir語言中 Registry.register 相關用法介紹如下。

用法:

register(registry, key, value)
(從 1.4.0 開始)
@spec register(registry(), key(), value()) ::
  {:ok, pid()} | {:error, {:already_registered, pid()}}

registry 中的給定 key 下注冊當前進程。

還必須給出與此注冊相關聯的值。每當調度或進行鍵查找時都會檢索此值。

此函數返回 {:ok, owner}{:error, reason}owner 是負責 PID 的注冊表分區中的 PID。所有者會自動鏈接到調用者。

如果注冊表具有唯一鍵,它將返回 {:ok, owner} ,除非該鍵已經與 PID 關聯,在這種情況下它返回 {:error, {:already_registered, pid}}

如果注冊表有重複鍵,則允許在同一鍵下從當前進程進行多次注冊。

例子

在唯一注冊表下注冊不允許多個條目:

iex> Registry.start_link(keys: :unique, name: Registry.UniqueRegisterTest)
iex> {:ok, _} = Registry.register(Registry.UniqueRegisterTest, "hello", :world)
iex> Registry.register(Registry.UniqueRegisterTest, "hello", :later)
{:error, {:already_registered, self()}}
iex> Registry.keys(Registry.UniqueRegisterTest, self())
["hello"]

但是,對於重複的注冊表,這是可能的:

iex> Registry.start_link(keys: :duplicate, name: Registry.DuplicateRegisterTest)
iex> {:ok, _} = Registry.register(Registry.DuplicateRegisterTest, "hello", :world)
iex> {:ok, _} = Registry.register(Registry.DuplicateRegisterTest, "hello", :world)
iex> Registry.keys(Registry.DuplicateRegisterTest, self())
["hello", "hello"]

相關用法


注:本文由純淨天空篩選整理自elixir-lang.org大神的英文原創作品 Registry.register(registry, key, value)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。