gpt4 book ai didi

elixir - 当 worker 重新启动时,主管保持状态

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

我有一个 AgentTest 作为保持状态的工作人员,还有一个 Supv 作为监视器 AgentTest

 defmodule AgentTest do
use Agent

def start_link(state) do
Agent.start_link(fn -> state end, name: :test)
end

def incr do
Agent.get_and_update(:test, fn state -> {state, state + 1} end)
end

def crash do
Agent.stop(:test, :crash)
end

def get do
Agent.get(:test, fn state -> state end)
end
end

defmodule Supv do
use Supervisor

def start_link do
Supervisor.start_link(Supv, [])
end

def init(_arg) do
Supervisor.init([
{AgentTest, 1}
], strategy: :one_for_one)
end
end

我在iex中尝试过,重启后状态不再保留:

iex(2)> Supv.start_link
{:ok, #PID<0.99.0>}
iex(3)> AgentTest.incr
1
iex(4)> AgentTest.incr
2
iex(5)> AgentTest.get
3
iex(6)> AgentTest.get
3
iex(7)> AgentTest.crash
:ok
iex(8)>
10:03:26.560 [error] GenServer :test terminating
** (stop) :crash
Last message: []
State: 3

nil
iex(9)> AgentTest.get
1

Supv重启时如何保持AgentTest状态?

我使用的是 Elixir 1.5

最佳答案

为了保留状态,您可以运行一个单独的进程,该进程将存储一个隐藏值。

defmodule Supv do
use Supervisor

def start_link do
children = [
worker(Stash, [1]),
worker(AgentTest, [])
]

Supervisor.start_link(Supv, children)
end

def init(children) do
supervise children, strategy: :one_for_one
end
end

当主 AgentTest 进程终止时,它将其当前值放入存储中。当进程重新启动时,它会从存储中获取值:

defmodule AgentTest do
use Agent

def start_link do
Agent.start_link(fn -> Stash.get() end, name: :test)
end

def incr do
Agent.get_and_update(:test, fn state -> {state, state + 1} end)
end

def crash do
Stash.update(get())

Agent.stop(:test, :crash)
end

def get do
Agent.get(:test, fn state -> state end)
end
end

存储过程可以是一个简单的代理:

defmodule Stash do
use Agent

def start_link(initial_number) do
Agent.start_link(fn -> initial_number end, name: :stash)
end

def get do
Agent.get(:stash, fn state -> state end)
end

def update(number) do
Agent.update(:stash, fn _ -> number end)
end
end

为了简化示例,我将进程命名为 (:stash),但它的 pid 当然可以作为参数传递给 AgentTest .

关于elixir - 当 worker 重新启动时,主管保持状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45725525/

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