Skip to content

Instantly share code, notes, and snippets.

@darach
Created July 2, 2014 11:05
Show Gist options
  • Save darach/a37680b9a90616957380 to your computer and use it in GitHub Desktop.
Save darach/a37680b9a90616957380 to your computer and use it in GitHub Desktop.
ZMQ lazy pirate pattern - client - erlzmq2
#!/usr/bin/env escript
-module(lpc).
-mode(compile).
-define(request_timeout,2500). %% msecs, (> 1000!)
-define(request_retries,3). %% before we abandon
-define(recv_timeout_enable,true).
-define(recv_timeout,2500). %% msecs
main(_Args) ->
%% Append project ebin to path
true = code:add_pathz(filename:dirname(escript:script_name()) ++ "/../ebin"),
loop(1,connect(),[{retries,?request_retries},{timeout,?request_timeout},{connect,fun connect/0}]).
connect() ->
%% Create ZMQ client with REQ client socket pattern and connect
{ok, Ctx} = erlzmq:context(),
{ok, Sock} = erlzmq:socket(Ctx, req),
ok = erlzmq:connect(Sock, "tcp://localhost:4321"),
case ?recv_timeout_enable of
true -> erlzmq:setsockopt(Sock, rcvtimeo, ?recv_timeout);
_ -> ignore
end,
%% Configure socket to not wait at close
%% czmq:zctx_set_linger(Ctx, 0),
{Ctx,Sock}.
loop(Sequence,{Ctx,Sock},Options) ->
{value,{_,Retries}} = lists:keysearch(retries,1,Options),
{value,{_,Timeout}} = lists:keysearch(timeout,1,Options),
loop(0,{Ctx,Sock},Retries,Timeout).
loop(Sequence,{Ctx,Sock},Retries,Timeout) ->
{_,_,Connection} = send(Sequence,{Ctx,Sock},lazy_pirate,Retries,Timeout),
timer:sleep(1000),
loop(Sequence+1,Connection,Retries,Timeout).
send(Sequence,_,lazy_pirate,0,Timeout) ->
io:format("Fail: ~p~n", [Sequence]),
{error, Sequence, connect()};
send(Sequence,{Ctx,Sock},lazy_pirate,Retries,Timeout) ->
io:format("Trying ~p ~p~n", [Sequence,(4 - Retries)]),
case erlzmq:send(Sock,integer_to_binary(Sequence)) of
ok -> case erlzmq:recv(Sock) of
{ok,Reply} -> io:format("Pass: ~p~n", [Sequence]), {ok,Reply,{Ctx,Sock}};
{error, eagain} -> send(Sequence,connect(),lazy_pirate,Retries-1,Timeout)
end;
error -> send(Sequence,connect(),lazy_pirate,Retries-1,Timeout)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment