[我是Erlang的新秀,累了为Spider编写代码:
-module(http).
-compile([export_all]).
init() ->
ssl:start(),
inets:start(),
register(m, spawn(fun() -> loop() end)),
register(fetch, spawn(fun() -> x() end)),
ok.
start() ->
L1 = [114689,114688,114691,114690], % detail page id
lists:map(fun(Gid) ->
io:format("~p ~n", [Gid]),
fetch ! {go, Gid}
end, L1),
m ! done,
done.
main(_) ->
init(),
start().
loop() ->
io:fwrite("this is in loop!!"),
receive
{no_res, Gid} ->
io:format("~p no res ! ~n", [Gid]),
loop();
{have_res, Gid} ->
io:format("~p have res ! ~n", [Gid]),
loop();
done ->
io:format("wowowow", [])
end.
x() ->
receive
{go, Gid} ->
http_post(Gid);
_ ->
ready
end.
http_post(Gid) ->
URL = "https://example.com", % url demo
Type = "application/json",
ReqArr = ["[{\"id\": \"", integer_to_list(Gid), "\"}]"],
ReqBody = string:join(ReqArr, ""),
case httpc:request(post, {URL, [], Type, ReqBody}, [], []) of
{ok, {_, _, ResBody}} ->
if
length(ResBody) =:= 0 ->
io:format("Y: ~p ~n", [Gid]);
m ! {no_res, Gid};
true ->
io:format("N: ~p ~n", [Gid])
m ! {have_res, Gid}
end;
{error, Reason} ->
io:format("error cause ~p~n", [Reason]);
_ ->
io:format("error cause ~n", [])
end.
现在,当我执行代码时,过程将立即终止,登录:
我有两个问题:
L1
中有成千上万个ID,如何解决?产生几十个演员?如果是,您如何确定哪个演员要receive
哪个ID?1)而不是在loop()
周围包裹一个匿名函数:
register(m, spawn(fun() -> loop() end)),
您可以拨打spawn/3:
register(m, spawn(?MODULE, loop, []) ),
这里相同:
register(fetch, spawn(fun() -> x() end)),