[erlang-questions] Message Loop in Gen_Server

Lee Sylvester <>
Wed Apr 17 21:08:39 CEST 2013


Thanks, Tim.  I'll take a look.  I've been searching for examples, but they're not that common.  I'll have a go at searching on amqp_gen_consumer… I'm sure that'll throw something up :-)

Regards,
Lee


On 17 Apr 2013, at 20:05, Tim Watson <> wrote:

> Hi,
> 
> When you subscribe, channel messages will be sent to the supplied Pid whenever something happens, e.g., basic.deliver etc.
> 
> So you don't need to go into a loop, because you've passed self() which in init/1 is the server's process id. What you do instead is to code your handle_info/2 clauses to deal with the AMQP messages.
> 
> You might want to take a look at amqp_gen_consumer as an alternative to gen_server for this as well.
> 
> Cheers,
> Tim
> 
> On 17 Apr 2013, at 18:33, Lee Sylvester <> wrote:
> 
>> Hey guys,
>> 
>> So, I've hit a "best practice" conundrum in OTP; I have a server utilising gen_server for a RabbitMQ consumer.  In the init of that gen_server, I'm setting up a RabbitMQ connection, but I also need to start a loop.  My guess was that I shouldn't call this before init exits, as I was passing the Connection and Channel objects to state for handling elsewhere.  If I handle the loop in init, surely it will never return?
>> 
>> To simplify what I'm saying (as I'm confusing myself here), here's my code:
>> 
>> init([]) ->
>>   {ok, Connection} = amqp_connection:start(#amqp_params_network{ host="localhost" }),
>>   {ok, Channel} = amqp_connection:open_channel(Connection),
>>   amqp_channel:call(Channel, #'exchange.declare'{exchange = <<"user_msgs">>,
>>                                                  type = <<"direct">>}),
>>   #'queue.declare_ok'{queue = Queue} =
>>       amqp_channel:call(Channel, #'queue.declare'{exclusive = true}),
>>   State = {Channel, Connection},
>>   amqp_channel:call(Channel, #'queue.bind'{exchange = <<"user_msgs">>,
>>                                             routing_key = term_to_binary(node(self())),
>>                                             queue = Queue}),
>>   amqp_channel:subscribe(Channel, #'basic.consume'{queue = Queue,
>>       no_ack = true}, self()),
>>   receive
>>       #'basic.consume_ok'{} -> ok
>>   end,
>>   loop(Channel),
>>   {ok, State}.
>> 
>> Now, if I don't put the loop in my init, then how can I be sure that the loop is called every time the gen_server restarts?  Can someone please suggest the "right" way to call the loop in my gen_server?
>> 
>> Thanks loads,
>> Lee
>> _______________________________________________
>> erlang-questions mailing list
>> 
>> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list