I have a receive block in erlang.If there is a timeout in my gen-server it returns ok but not the actual value.How to return actual value

4zcjmb1e  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(157)

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

-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),
    {ok, 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, _From, State) ->
    io:format("received other handle_call message: ~p~n", [Message]),
    {reply, ok, State}.
handle_cast(stop, State) ->
    {stop, normal, State};
handle_cast(Message, State) ->
    io:format("received other handle_cast call : ~p~n", [Message]),
    {noreply, State}.
handle_info(Message, State) ->
    io:format("received handle_info message : ~p~n", [Message]),
    {noreply, 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.`
jv2fixgn

jv2fixgn1#

您的loop/0函数会评估receive陈述式。
receive语句在超时情况下的计算结果是其after块中的表达式列表的计算结果。在您的示例中,即io:format(" Server timeout "),它输出Server timeout并计算为ok
这就是为什么整个函数的计算结果为(即“返回”)ok

相关问题