微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我在 erlang 中有一个接收块如果我的 gen-server 中存在超时,它返回正常但不是实际值如何返回实际值

如何解决我在 erlang 中有一个接收块如果我的 gen-server 中存在超时,它返回正常但不是实际值如何返回实际值

%% 有时我的循环返回正常,因为超时如何以正确的方式编写此代码。当超时时,它只返回正常但不是我假设的实际值。在处理调用中,我正在调用函数循环() 在 loop() 函数中,我收到一条带有接收子句的消息。现在我正在使用 loop2 函数将此数据发送到我的数据库,无论数据是否已成功保存,都从数据库返回响应并将响应返回给 loop()。但是如果超时,我的循环函数返回正常但不是实际值

 -module(getAccDataCons).
-behavIoUr(gen_server).
-include_lib("deps/amqp_client/include/amqp_client.hrl").
-export([start_link/0,stop/0]).
-export([init/1,handle_call/3,handle_cast/2,handle_info/2,code_change/3,terminate/2]).
-export([get_account/0]).
start_link() ->
    gen_server:start_link({local,?MODULE},?MODULE,[],[]).
stop() ->
    gen_server:cast(?MODULE,stop).
get_account() ->
    gen_server:call(?MODULE,{get_account}).
init(_Args) ->
    {ok,Connection} = amqp_connection:start(#amqp_params_network{host = "localhost"}),{ok,Channel} = amqp_connection:open_channel(Connection),Channel}.
handle_call({get_account},_From,State) ->
    amqp_channel:call(State,#'exchange.declare'{exchange = <<"get">>,type = <<"topic">>}),amqp_channel:call(State,#'queue.declare'{queue = <<"get_account">>,durable = true}),Binding =
        #'queue.bind'{exchange = <<"get">>,routing_key = <<"get.account">>,queue = <<"get_account">>},#'queue.bind_ok'{} = amqp_channel:call(State,Binding),io:format(" [*] Waiting for logs. To exit press CTRL+C~n"),amqp_channel:subscribe(State,#'basic.consume'{queue = <<"get_account">>,no_ack = true},self()),Returned =loop(),io:format("~nReti=~p",[Returned]),{reply,Returned,State};
handle_call(Message,State) ->
    io:format("received other handle_call message: ~p~n",[Message]),ok,State}.
handle_cast(stop,State) ->
    {stop,normal,State};
handle_cast(Message,State) ->
    io:format("received other handle_cast call : ~p~n",{noreply,State}.
handle_info(Message,State) ->
    io:format("received handle_info message : ~p~n",State}.
code_change(_OldVer,State,_Extra) ->
    {ok,State}.
terminate(Reason,_State) ->
    io:format("server is terminating with reason :~p~n",[Reason]).
    loop()->
        receive
         #'basic.consume_ok'{} ->
             loop();
             {#'basic.deliver'{},Msg} ->
                 #amqp_msg{payload = Payload} = Msg,Value=loop2(Payload),Value
     after 200->
     io:format("timeout")
     end.`

解决方法

您的 loop/0 函数计算 receive 语句。

在超时的情况下评估 receive 语句的结果是评估其 after 块中的表达式列表的结果。在您的情况下,它是 io:format(" Server timeout ") 并打印出 Server timeout 并计算为 ok

这就是为什么整个函数的计算结果为(即“返回”)ok

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。