我的個人博客網站雲諾說上線啦!所有文章都搬到新地址了,點擊圍觀吧!
RabbitMQ是一些概念、安裝、一鍵實現這個簡單的HelloWorld程序的步驟和可能遇到的問題這裏都不講了, 有疑問的可以看看這篇文章。這裏主要是用Erlang來實現這個簡單程序。RabbitMQ的Erlang庫可以從這裏下載,下載解壓後直接在linux下make一下就OK了。
make過程中會自己下載一些依賴庫,都在deps下。這些依賴庫都是以application的方式運行的,所以我們只要運行amqp_client:start().就可以啓動整個client程序了。
好了, 廢話不多說了, 直接上代碼!!
消費者:
-module(mod_receive).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([start_link/0]).
-include("common.hrl").
-record(state, {}).
-define(SERVER,hello_receiver).
start_link() ->
gen_server:start_link({local,?SERVER}, ?MODULE, [], []).
init([]) ->
start(),
{ok, #state{}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'basic.consume_ok',_}, State) ->
{noreply, State};
handle_info({#'basic.deliver'{},#amqp_msg{payload=Msg}}, State) ->
io:format(" receive messages is ~p~n",[Msg]),
{noreply, State};
handle_info(Info, State) ->
io:format("unknown messages is ~p~n", [Info]),
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
start() ->
Params = #amqp_params_network{host=?HOST,username=?USER_NAME,password=?PASSWORD},
case amqp_connection:start(Params) of
{ok,ConnectionPid} ->
{ok, Channel} = amqp_connection:open_channel(ConnectionPid),
amqp_channel:call(Channel, #'queue.declare'{queue = <<"hello">>}),
io:format(" Waiting for messages......~n"),
amqp_channel:subscribe(Channel, #'basic.consume'{queue = <<"hello">>,no_ack = true}, self());
{error,Resaon} ->Resaon
end.
生產者:
-module(mod_send).
-export([send/0]).
-include("common.hrl").
send() ->
Params = #amqp_params_network{host=?HOST,username=?USER_NAME,password=?PASSWORD},
case amqp_connection:start(Params) of
{ok,ConnectionPid} ->
{ok, Channel} = amqp_connection:open_channel(ConnectionPid),
amqp_channel:call(Channel, #'queue.declare'{queue = <<"hello">>}),
amqp_channel:cast(Channel,
#'basic.publish'{
exchange = <<"">>,
routing_key = <<"hello">>},
#amqp_msg{payload = <<"Hello World!">>}),
io:format("Sent 'Hello World!'~n"),
ok = amqp_channel:close(Channel),
ok = amqp_connection:close(ConnectionPid),
ok;
{error,Reason} ->Reason
end.
common頭文件:
-include("amqp_client_internal.hrl").
-define(USER_NAME , <<"test">>).
-define(PASSWORD , <<"test">>).
-define(HOST , "192.168.249.128").
-define(PORT , 5672).
運行結果:
祝生活愉快!!!