版权声明:本文为博主原创文章,如果转载请给出原文链接:http://doofuu.com/article/4156136.html
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).
运行结果:
共有 0 条评论 - RabbitMQ之入门HelloWorld(Erlang)