我正在对 Logan/Merritt/Carlson 的简单缓存、第 6 章、第 149-169 页、Erlang 和 OTP in Action 进行轻微修改。到目前为止,没有代码更改,只是重命名模块。
我启动应用程序:
application:start(gridz).
ok
我插入一个项目:
gridz_maker:insert(blip, blop).
我收到此错误:
** exception error: no match of right hand side value
{error,
{function_clause,
[{gridz_edit,init,
[{blop,86400}],
[{file,"src/gridz_edit.erl"},{line,51}]},
{gen_server,init_it,6,
[{file,"gen_server.erl"},{line,304}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,227}]}]}}
in function gridz_maker:insert/2 (src/gridz_maker.erl, line 15)
这是代码:
insert(Key, Value) ->
case gridz_store:lookup(Key) of
{ok, Pid} -> gridz_edit:replace(Pid, Value);
{error, _} -> {ok, Pid} = gridz_edit:create(Value), %% line 15
gridz_store:insert(Key, Pid)
end.
我看第 15 行:
{error, _} -> {ok, Pid} = gridz_edit:create(Value),
我预计会出现错误,因为这是一个新项目。gridz:edit 是一个 gen_server(Logan 等人中的 sc_element。)这是 create/1 的代码:
create(Value) ->
create(Value, ?DEFAULT_LEASE_TIME).
create(Value, LeaseTime) ->
gridz_sup:start_child(Value, LeaseTime).
这是 gridz_sup:start_child/2 的代码:
start_child(Value, LeaseTime) ->
supervisor:start_child(?SERVER, [Value, LeaseTime]).
init([]) ->
Grid = {gridz_edit, {gridz_edit, start_link, []},
temporary, brutal_kill, worker, [gridz_edit]},
Children = [Grid],
RestartStrategy = {simple_one_for_one, 0, 1},
{ok, {RestartStrategy, Children}}.
如果我直接执行 supervisor:start_child/2 ,这就是我得到的:
{error,{function_clause,[{gridz_edit,init,
[{blop,50400}],
[{file,"src/gridz_edit.erl"},{line,51}]},
{gen_server,init_it,6,
[{file,"gen_server.erl"},{line,304}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,227}]}]}}
gridz_edit 中的第 51 行是一个 init 函数:
init([Value, LeaseTime]) ->
Now = calendar:local_time(),
StartTime = calendar:datetime_to_gregorian_seconds(Now),
{ok,
#state{value = Value,
lease_time = LeaseTime,
start_time = StartTime},
time_left(StartTime, LeaseTime)}.
如果我直接执行它,它可以工作:
120> gridz_edit:init([blop, (60 * 60 * 24)]).
{ok,{state,blop,86400,63537666408},86400000}
所以现在我很困惑。我错过了什么?为什么 supervisor:start_child/2 会抛出错误?
谢谢,
LRP