gen_server:call - 如何发送消息

gen_server:call - how to send message

现在我在玩 gen_server

我有两个 mod 规则 - 一个是 Gen Server mod,第二个 - 逻辑 module

并想通过 gen_server:call

向 PID 发送消息

这里是代码片段:

lookup_by_date(FromTime, ToTime) ->
    gen_server:call({global, ?MODULE}, {lookup_by_date,FromTime,ToTime}).

这里是 handle_call 函数:

handle_call({lookup_by_date, FromTime, ToTime}, _From, _State) ->
    FromSec = calendar:datetime_to_gregorian_seconds(FromTime),
    ToSec = calendar:datetime_to_gregorian_seconds(ToTime),
    Pid = spawn(fun()-> logic:handler() end),
    {reply, Pid !{lookup_by_date, FromSec, ToSec}, _State};

a 和逻辑 mod 代码:

lookup_by_date(FromTime, ToTime) -> lookup_by_date(FromTime, ToTime, ets:first(auth), []).
lookup_by_date(_FromTime, _ToTime, '$end_of_table', Acc) -> {reply, Acc, ok};
lookup_by_date(FromTime, ToTime, Key, Acc) ->
    case ets:lookup(auth, Key) of
        [{Login, Pass, TTL, Unix, Unix2}] ->
            F = calendar:datetime_to_gregorian_seconds(Unix2),
        T = calendar:datetime_to_gregorian_seconds(Unix2),
        if
            F >= FromTime, T =< ToTime -> NewAcc = [{Login, Pass, TTL, Unix, Unix2}|Acc],
        N = ets:next(auth, Key),
            lookup_by_date(FromTime, ToTime, N, NewAcc);
        true -> N = ets:next(auth, Key),
                    lookup_by_date(FromTime, ToTime, N, Acc)
         end
        end.

handler() ->
  receive
      {lookup_by_date, FromTime, ToTime}->
          lookup_by_date(FromTime, ToTime),
            handler();
      Other->
        io:format("Error message for ~p~n" ,[Other]),
      handler()
  end.

但我收到错误(实际上不是错误)

2> c(cache_server).

{好的,cache_server}

3> c(逻辑).

{好的,逻辑}

4> cache_server:start([{ttl, 15000}]).

{好的,<0.73.0>}

5> cache_server:insert(测试, root, 15000).

{auth,test,root,15000,1484309726435, {{2017,1,13},{14,15,11}}}

6> cache_server:lookup_by_date({{2017,1,13},{14,15,11}},{{2017,1,13},{14,15,11}})。

{lookup_by_date,63651536111,63651536111}


我正在从 - {reply, Pid !{lookup_by_date, FromSec, ToSec}, _State} 接收数据;

但没有从 "logic:lookup_by_date" 函数接收数据

反正你有没有告诉我正确的方向,因为我有点卡住了。 谢谢...

在您的代码中,对 gen_server 调用的回复是:

Pid !{lookup_by_date, FromSec, ToSec}

在 Erlang 中,消息是异步的,它们只是发送到进程,所以这段代码不等待响应,它只是 returns,立即发送您发送的消息。这就是您收到回复 {lookup_by_date, FromSec, ToSec}.

的原因

在您的情况下,您不必生成进程,只需调用 lookup_by_date 函数即可:

handle_call({lookup_by_date, FromTime, ToTime}, _From, _State) ->
    FromSec = calendar:datetime_to_gregorian_seconds(FromTime),
    ToSec = calendar:datetime_to_gregorian_seconds(ToTime),
    {reply, logic:lookup_by_date(FromSec, ToSec), _State};

注意:您的 gen_server 不使用结果,它的状态不会被请求修改,因此您可以直接调用函数 lookup_by_date 并在其中包含时间转换。