rabbitmq技术的一些感悟

Rabbitmq

初识rabbitmq

RabbitMQ是流行的开源消息队列系统,用erlang语言开发。RabbitMQAMQP(高级消息队列协议)的标准实现。如果不熟悉AMQP,直接看RabbitMQ的文档会比较困难。不过它也只有几个关键概念,这里简单介绍

几个概念说明:

Broker:简单来说就是消息队列服务器实体。
Exchange:消息交换机,它指定消息按什么规则,路由到哪个队列。
Queue:消息队列载体,每个消息都会被投入到一个或多个队列。
Binding:绑定,它的作用就是把exchangequeue按照路由规则绑定起来。
Routing Key:路由关键字,exchange根据这个关键字进行消息投递。
vhost:虚拟主机,一个broker里可以开设多个vhost,用作不同用户的权限分离。
producer:消息生产者,就是投递消息的程序。
consumer:消息消费者,就是接受消息的程序。
channel:消息通道,在客户端的每个连接里,可建立多个channel,每个channel代表一个会话任务。

由Exchange,Queue,RoutingKey三个才能决定一个从Exchange到Queue的唯一的线路。

消息队列的使用过程大概如下:

1)客户端连接到消息队列服务器,打开一个channel
  (2)客户端声明一个exchange,并设置相关属性。
  (3)客户端声明一个queue,并设置相关属性。
  (4)客户端使用routing key,在exchangequeue之间建立好绑定关系。
  (5)客户端投递消息到exchange

exchange接收到消息后,就根据消息的key和已经设置的binding,进行消息路由,将消息投递到一个或多个队列里。

exchange也有几个类型,完全根据key进行投递的叫做Direct交换机,例如,绑定时设置了routing key”abc”,那么客户端提交的消息,只有设置了key”abc”的才会投递到队列。对key进行模式匹配后进行投递的叫做Topic交换机,符号”#”匹配一个或多个词,符号”*”匹配正好一个词。例如”abc.#”匹配”abc.def.ghi””abc.*”只匹配”abc.def”。还有一种不需要key的,叫做Fanout交换机,它采取广播模式,一个消息进来时,投递到与该交换机绑定的所有队列。

RabbitMQ支持消息的持久化,也就是数据写在磁盘上,为了数据安全考虑,我想大多数用户都会选择持久化。消息队列持久化包括3个部分:
  (1exchange持久化,在声明时指定durable => 1
  (2queue持久化,在声明时指定durable => 1
  (3)消息持久化,在投递时指定delivery_mode=> 21是非持久化)

如果exchangequeue都是持久化的,那么它们之间的binding也是持久化的。如果exchangequeue两者之间有一个持久化,一个非持久化,就不允许建立绑定。

安装开发环境和库

1.将目录中的librabbitmq.so.1放到目录 /usr/local/lib/librabbitmq.so.1

2.安装rabbitm需要的环境和库

yum install -y ncurses-devel

yum install gcc

yum install g++

yum install cmake

yum install make

yum install php

yum install mysql

yum install php-process

yum install php-devel

yum install mysql-server

#安装php的amq支持扩展

wget http://pecl.php.net/get/amqp-1.0.3.tgz

tar zxvf amqp-1.0.3.tgz

cd amqp-1.0.3

/usr/bin/phpize

./configure--with-php-config=/usr/bin/php-config --with-amqp

make && make install

#php.ini 添加

vi /etc/php.ini

extension="amqp.so"

#安装erlang支持

wgethttp://www.erlang.org/download/otp_src_R15B01.tar.gz

tar -zxvf otp_src_R15B01.tar.gz

cd otp_src_R15B01

./configure --prefix=/home/erlang--without-javac

make && make install

ln -s /home/erlang/bin/erl/usr/local/bin/erl

3. 安装rabbitma

 解压rabbitmq-server-generic-unix-3.3.4.tar

 进入sbin目录:

    启动rabbitmq服务,执行 nohup./rabbitmq-server start &

启动rabbitmq服务器以及命令

当第一次启动服务,检测数据库是否未初始化或者被删除,它会用下面的资源初始化一个新的数据库:

一个命名为 / 的虚拟宿主一个名为guest密码也为guest的用户,他拥有/虚拟宿主的所有权限如果你的中间件是公开访问的,最好修改guest用户的密码。管理概观rabbitmqctl 是RabbitMQ中间件的一个命令行管理工具。它通过连接一个中间件节点执行所有的动作。本地节点默认被命名为”rabbit”。可以通过这个命令前使用”-n”标志明确的指定节点名称, 例如:# rabbitmqctl -n rabbit@shortstop add_user tonyg changeit

这个命令指示RabbitMQ中间件在rabbit@shortstop 节点创建一个tonyg/changeit的用户。

在一个名为”server.example.com”的主机,RabbitMQ Erlang节点的名称通常是rabbit@server(除非RABBITMQ_NODENAM在中间件启动时候被设置)。hostnam -s 的输出通常是”@”符号正确的后缀。rabbitmqctl 默认产生详细输出。通过”-q”标示可选择安静模式。rabbitmqctl -q status应用和集群管理1.停止RabbitMQ应用,关闭节点

# rabbitmqctl stop

2.停止RabbitMQ应用

# rabbitmqctl stop_app

3.启动RabbitMQ应用

# rabbitmqctl start_app

4.显示RabbitMQ中间件各种信息

# rabbitmqctl status

5.重置RabbitMQ节点

# rabbitmqctl reset

# rabbitmqctl force_reset

从它属于的任何集群中移除,从管理数据库中移除所有数据,例如配置过的用户和虚拟宿主, 删除所有持久化的消息。

force_reset命令和reset的区别是无条件重置节点,不管当前管理数据库状态以及集群的配置。如果数据库或者集群配置发生错误才使用这个最后的手段。

注意:只有在停止RabbitMQ应用后,reset和force_reset才能成功。

6.循环日志文件

# rabbitmqctl rotate_logs[suffix]

7.集群管理

# rabbitmqctl cluster clusternode…

用户管理

1.添加用户

# rabbitmqctl add_user username password

2.删除用户

# rabbitmqctl delete_user username

3.修改密码

# rabbitmqctl change_password usernamenewpassword

4.列出所有用户

# rabbitmqctl list_users

权限控制1.创建虚拟主机

# rabbitmqctl add_vhost vhostpath

2.删除虚拟主机

# rabbitmqctl delete_vhost vhostpath

3.列出所有虚拟主机

# rabbitmqctl list_vhosts

4.设置用户权限

# rabbitmqctl set_permissions [-pvhostpath] username regexp regexp regexp

5.清除用户权限

# rabbitmqctl clear_permissions [-pvhostpath] username

6.列出虚拟主机上的所有权限

# rabbitmqctl list_permissions [-pvhostpath]

7.列出用户权限

# rabbitmqctl list_user_permissionsusername

 

例子:

添加  rabbitmqctl add_vhost az

rabbitmqctl set_permissions -p az guest".*" ".*" ".*"

 

接口描述

amqp_connection_state_tamqp_new_connection(void);

    接口说明:声明一个新的amqp connection

intamqp_open_socket(char const *hostname, int portnumber);

    接口说明:获取socket.

    参数说明:hostname        RabbitMQ server所在主机

                 portnumber     RabbitMQ server监听端口   

 

voidamqp_set_sockfd(amqp_connection_state_t state,int sockfd);

     接口说明:将amqp connectionsockfd进行绑定

amqp_rpc_reply_tamqp_login(amqp_connection_state_t state, char const *vhost,intchannel_max,int frame_max,int heartbeat,amqp_sasl_method_enum sasl_method,...);

    接口说明:用于登录RabbitMQ server,主要目的为了进行权限管理;

    参数说明:state    amqpconnection

                 vhost   rabbit-mq的虚机主机,是rabbit-mq进行权限管理的最小单位

                 channel_max  最大链接数,此处设成0即可

                 frame_max  和客户端通信时所允许的最大的frame size.默认值为131072,增大这个值有助于提高吞吐,降低这个值有利于降低时延

                 heartbeat 含义未知,默认值填0

                 sasl_method  用于SSL鉴权,默认值参考后文demo

 

amqp_channel_open_ok_t*amqp_channel_open(amqp_connection_state_t state, amqp_channel_t channel);

    接口说明:用于关联connchannel

 

amqp_exchange_declare_ok_t*amqp_exchange_declare(amqp_connection_state_t state, amqp_channel_t channel,amqp_bytes_t exchange, amqp_bytes_t type, amqp_boolean_t passive,amqp_boolean_t durable, amqp_table_t arguments); 

    接口说明:声明declare

    参数说明:state

                 channel

                 exchange

                 type     "fanout" "direct" "topic"三选一

                 passive

                 curable

                 arguments

 

amqp_queue_declare_ok_t*amqp_queue_declare(amqp_connection_state_t state, amqp_channel_t channel,amqp_bytes_t queue, amqp_boolean_t passive, amqp_boolean_t durable,amqp_boolean_t exclusive, amqp_boolean_t auto_delete, amqp_table_targuments); 

    接口说明:声明queue

    参数说明:state   amqp connection

                 channel 

                 queue  queue name

                 passive 

                 durable  队列是否持久化

                 exclusive  当前连接不在时,队列是否自动删除

                 aoto_delete 没有consumer时,队列是否自动删除

                 arguments 用于拓展参数,比如x-ha-policy用于mirrored queue

 

amqp_queue_bind_ok_t*amqp_queue_bind(amqp_connection_state_t state, amqp_channel_t channel,amqp_bytes_t queue, amqp_bytes_t exchange, amqp_bytes_t routing_key, amqp_table_t arguments);

    接口说明:声明binding    

 

amqp_basic_qos_ok_t*amqp_basic_qos(amqp_connection_state_t state, amqp_channel_t channel, uint32_tprefetch_size, uint16_t prefetch_count, amqp_boolean_t global);

     接口说明:qos quality of service,我们这里使用主要用于控制预取消息数,避免消息按条数均匀分配,需要和no_ack配合使用

     参数说明:state

                  channel

                  prefetch_size bytes为单位,0unlimited

                  prefetch_count 预取的消息条数

                  global

 

amqp_basic_consume_ok_t*amqp_basic_consume(amqp_connection_state_t state, amqp_channel_t channel,amqp_bytes_t queue, amqp_bytes_t consumer_tag, amqp_boolean_t no_local,amqp_boolean_t no_ack, amqp_boolean_t exclusive, amqp_table_t arguments); 

     接口说明:开始一个queue consumer

     参数说明:state

                  channel

                  queue

                  consumer_tag

                  no_local

                  no_ack    是否需要确认消息后再从队列中删除消息

                  exclusive

                  arguments

 

int amqp_basic_ack(amqp_connection_state_tstate,amqp_channel_t channel,uint64_t delivery_tag,amqp_boolean_t multiple);

                    

intamqp_basic_publish(amqp_connection_state_t state,amqp_channel_tchannel,amqp_bytes_t exchange,amqp_bytes_t routing_key,amqp_boolean_tmandatory,amqp_boolean_t immediate,struct amqp_basic_properties_t_ const*properties,amqp_bytes_t body);

    接口说明:发布消息

    参数说明:state 

                 channel

                 exchange  

                 routing_key  exchange为默认“”时,此处填写queue_name,当exchangedirect,此处为binding_key

                 mandatory 参见参考文献2

                 immediate 同上

                 properties 更多属性,如何设置消息持久化,参见文后demo

                 body 消息体

 

amqp_rpc_reply_tamqp_channel_close(amqp_connection_state_t state,amqp_channel_t channel,intcode);

amqp_rpc_reply_tamqp_connection_close(amqp_connection_state_t state,int code);

intamqp_destroy_connection(amqp_connection_state_t state);



上一节文章主要是说了一下rabbitmq的安装以及搭建好环境的一些命令,以及常用的api调用,其实自从google被封掉之后,我之前收藏的很多技术连接都已经被禁止访问了,这个是多么可悲的一件事情啊,说多了都是泪。

     首先,我先写一段消费者的模块,建立连接,初始化amq以及销毁连接:

[cpp]  view plain copy
  1. Comsumer::Comsumer(){  
  2.   
  3. }  
  4. void Comsumer::init(){  
  5.     conn = amqp_new_connection();  
  6.     int sockfd = amqp_open_socket(g_logSrv.m_conf.m_hostname.c_str(), g_logSrv.m_conf.m_port);  
  7.     amqp_set_sockfd(conn,sockfd);  
  8.     LogServer::die_on_amqp_error(amqp_login(conn, g_logSrv.m_conf.m_vhosts.c_str(), 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,  g_logSrv.m_conf.m_username.c_str(),  g_logSrv.m_conf.m_psw.c_str()),"Logging in");  
  9.     amqp_channel_open(conn, (amqp_channel_t)g_logSrv.m_conf.m_channel);  
  10.     LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");  
  11.     for(list<ramqserverInfo>::iterator it = g_logSrv.m_conf.getAmqserverInfo.begin(); it != g_logSrv.m_conf.getAmqserverInfo.end(); it++){  
  12.         amqp_exchange_declare(conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(it->exchange.c_str()), amqp_cstring_bytes("direct"), 0, 0, amqp_empty_table);  
  13.         LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn), "Declaring exchange");  
  14.         amqp_queue_declare(conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(it->queue.c_str()), 0, 1, 0, 1, amqp_empty_table); // durable && auto-delete   
  15.         LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn), "Declaring queue");  
  16.           
  17.         amqp_queue_bind(conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(it->queue.c_str()), amqp_cstring_bytes(it->exchange.c_str()), amqp_cstring_bytes(it->route.c_str()), amqp_empty_table);    
  18.         LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn), "Binding");   
  19.   
  20.         amqp_basic_consume(conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(it->queue.c_str()), amqp_empty_bytes, 0, 1, 0, amqp_empty_table);  
  21.         LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn), "Consuming");  
  22.         connList.push_back(*it);  
  23.     }  
  24. }  
  25. Comsumer::~Comsumer(){  
  26.     if(conn == NULL){  
  27.         return;  
  28.     }  
  29.     LogServer::die_on_amqp_error(amqp_channel_close(conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, AMQP_REPLY_SUCCESS), "Closing channel");  
  30.     LogServer::die_on_amqp_error(amqp_connection_close(conn, AMQP_REPLY_SUCCESS), "Closing connection");      
  31.     LogServer::die_on_error(amqp_destroy_connection(conn), "Ending connection");  
  32. }  


 然后再写一段消费者的队列,他也是可持久化的队列:
[cpp]  view plain copy
  1. Producer::Producer(){  
  2. }  
  3. void Producer::init(){  
  4.     conn.conn = amqp_new_connection();  
  5.     int sockfd = amqp_open_socket(g_logSrv.m_conf.m_hostname.c_str(), g_logSrv.m_conf.m_port);  
  6.     amqp_set_sockfd(conn.conn,sockfd);  
  7.     LogServer::die_on_amqp_error(amqp_login(conn.conn, g_logSrv.m_conf.m_vhosts.c_str(), 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,  g_logSrv.m_conf.m_username.c_str(),  g_logSrv.m_conf.m_psw.c_str()),"Logging in");  
  8.     amqp_channel_open(conn.conn, (amqp_channel_t)g_logSrv.m_conf.m_channel);  
  9.     LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn.conn), "Opening channel");  
  10.     for(list<ramqserverInfo>::iterator it = g_logSrv.m_conf.commonAmqserver.begin(); it != g_logSrv.m_conf.commonAmqserver.end(); it++){  
  11.         amqp_exchange_declare(conn.conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(it->exchange.c_str()), amqp_cstring_bytes("direct"), 0, 0, amqp_empty_table);  
  12.         LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn.conn), "Declaring exchange");  
  13.         amqp_queue_declare(conn.conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(it->queue.c_str()), 0, 1, 0, 1, amqp_empty_table); // durable && auto-delete   
  14.         LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn.conn), "Declaring queue");  
  15.         amqp_queue_bind(conn.conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(it->queue.c_str()), amqp_cstring_bytes(it->exchange.c_str()), amqp_cstring_bytes(it->route.c_str()), amqp_empty_table);    
  16.         LogServer::die_on_amqp_error(amqp_get_rpc_reply(conn.conn), "Binding");       
  17.         connList.push_back(*it);  
  18.     }  
  19.     conn.props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;  
  20.     conn.props.content_type = amqp_cstring_bytes("text/plain");  
  21.     conn.props.delivery_mode = 2;  
  22. }  
  23. Producer::~Producer(){  
  24.     if(conn.conn == NULL){  
  25.         return;  
  26.     }  
  27.     LogServer::die_on_amqp_error(amqp_channel_close(conn.conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, AMQP_REPLY_SUCCESS), "Closing channel");  
  28.     LogServer::die_on_amqp_error(amqp_connection_close(conn.conn, AMQP_REPLY_SUCCESS), "Closing connection");  
  29.     LogServer::die_on_error(amqp_destroy_connection(conn.conn), "Ending connection");  
  30. }  
最后就是如何向rabbitmq中写消息和取消息了:

[cpp]  view plain copy
  1. void LogServer::WriteToAmqQueue(bool isQuick, string str){  
  2.     if(isQuick){  
  3.         uint8_t size = m_produce.connQuickList.size();  
  4.         uint8_t index = rand()%size;  
  5.         LogServer::die_on_error(amqp_basic_publish(m_produce.connQuick.conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(m_produce.connQuickList[index].exchange.c_str()), amqp_cstring_bytes(m_produce.connQuickList[index].route.c_str()), 0, 0, &m_produce.connQuick.props, amqp_cstring_bytes(str.c_str())), "Publishing");  
  6.     }else{  
  7.         uint8_t size = m_produce.connList.size();  
  8.         uint8_t index = rand()%size;  
  9.         LogServer::die_on_error(amqp_basic_publish(m_produce.conn.conn, (amqp_channel_t)g_logSrv.m_conf.m_channel, amqp_cstring_bytes(m_produce.connList[index].exchange.c_str()), amqp_cstring_bytes(m_produce.connList[index].route.c_str()), 0, 0, &m_produce.conn.props, amqp_cstring_bytes(str.c_str())), "Publishing");  
  10.     }     
  11. }  
  12. void LogServer::runAmqConsumer(){  
  13.     m_produce.init();  
  14.     m_consumer.init();  
  15.     uint32_t tickTime = time(0);  
  16.     while(1){  
  17.         amqp_rpc_reply_t ret;  
  18.         amqp_envelope_t envelope;  
  19.         memset(&envelope,0,sizeof(envelope));  
  20.         envelope.message.body.bytes={0};  
  21.         amqp_maybe_release_buffers(m_consumer.conn);  
  22.         ret = amqp_consume_message(m_consumer.conn, &envelope, NULL, 0);  
  23.   
  24.         if (ret.reply_type == AMQP_RESPONSE_NORMAL ){  
  25.             char* str = (char*)envelope.message.body.bytes;  
  26.             if(str == NULL){  
  27.                 return;  
  28.             }  
  29.             str[envelope.message.body.len-1] = '\0';  
  30.             LOG(DEBUG)("recv from amq:len:%d,%s\n",envelope.message.body.len,str);  
  31.             vector<string> vectStr;  
  32.             Util::strSplit(str, "|", vectStr);            
  33.             if(vectStr.size() > 8 && (g_logSrv.m_conf.quickWords.find(vectStr[8]) != g_logSrv.m_conf.quickWords.end())){  
  34.                 WriteToAmqQueue(true,str);  
  35.             }  
  36.             else  
  37.             {  
  38.                 WriteToAmqQueue(false,str);  
  39.             }  
  40.             amqp_destroy_envelope(&envelope);  
  41.         //  pushMsgQueue(str);  
  42.             str = NULL;  
  43.         }  
  44.         else{  
  45.             amqp_destroy_envelope(&envelope);  
  46.             return;  
  47.         }  
  48.   
  49.         if(tickTime + FAMETICK < time(0) && m_conf.loadConfig() != 0){  
  50.             tickTime = time(0);  
  51.             if(LogServer::m_stop == true){  
  52.                 m_produce.init();  
  53.                 m_consumer.init();  
  54.                 stop();  
  55.             }  
  56.             continue;  
  57.         }  
  58.     }  
  59. }  



转载 :http://blog.csdn.net/pbymw8iwm/article/details/38686607

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值