RabbitMQ队列

RabbitMQ并不是python内置的模块,而是一个需要额外安装的程序,安装完毕后可通过python中内置的pika模块来调用MQ发送或接收队列请求

RabbitMQ收到一条message时不会直接发给queue, 它必须经过exchange

通过使用pika第三方库来连接import pika
设置登陆认证,用户名+密码+端口pika.URLParameters(url)
建立连接connectionconnection = pika.BlockingConnection(pika.ConnectionParameters(url))
建立channelchannel = connection.channel()
创建exchange,publisher只知道把消息送给exchange,type我们用‘direct’channel.exchange_declare(exchange=_起个名,exchange_type=‘direct’,durable=True)
创建消息队列,设置消息持久化channel.queue_declare(queue=‘hello’, durable=True)
bind exchange和queuechannel.queue_bind(exchange=_exchange,queue=_queue,routing_key=peer-ip)
发送消息channel.basic_publish(exchange=’’, routing_key=‘peer-ip’(作为标识), body=‘hello world!’,properties=如下)properties里面只包含类型,模式,优先级 properties=pika.BasicProperties(body里面是要发送到rabbitmq的数据 content_type=‘application/json’,delivery_mode=1,priority=_priority

consumer是周期性不断运行的程序,一直在监听等待处理rabbitmy发来的message,目前我遇到处理的情况是监听探针发来的BGP报文,主要针对异样报文,比如物理链路down掉,而我们的控制器并不知道,还是正常下发policy就会出错,所以此时需要把已下发depolicy撤回,并在可视化界面显示

def main():
    try:
        prapare()    #连接数据库和rabbitmq的url
        peer_consumer = setup_consumer()  #指定queen=peer_ip,routing_key=peer_ip,worker
        try:
            peer_consumer.run()
        except KeyboardInterrupt:
            peer_consumer.stop()
    except:
        print traceback.format_exc()
   
def run(self):
    self._connection = self.connect()  #创建连接
    self._connection.ioloop.start()

# 连接到rabbitmq
def connect(self):
    LOG.info('Connecting to rabbitmq server')
    return pika.SelectConnection(self.parameters, self.on_connection_open, stop_ioloop_on_close=False)
 
# 开启连接                           
def on_connection_open(self, unused_connection):
    LOG.info('Connection opened')
    self.add_on_connection_close_callback()
    self.open_channel()       

# 创建channel
def open_channel(self):
    LOG.info('Creating a new channel')
    self._connection.channel(on_open_callback=self.on_channel_open)

# 创建queue                       
def on_channel_open(self, channel):
    LOG.info('Channel opened')
    self._channel = channel
    self.add_on_channel_close_callback()  #处理异常关闭的情况
    self.setup_queue(self.QUEUE)        #创建queue               

#定义queue的同时指定其对应的消费者
def setup_queue(self, queue_name):
    LOG.info('Declaring queue %s', queue_name)
    self._channel.queue_declare(callback=self.start_consuming(), queue=queue_name, durable=True)
    self._channel.basic_qos(prefetch_count=1)

#消费者收到message
def start_consuming(self):
    LOG.info('Issuing consumer related RPC commands')
    self.add_on_cancel_callback()
    self._consumer_tag = self._channel.basic_consume(self.on_message, self.QUEUE)

# 消费者开始处理message
def on_message(self, unused_channel, basic_deliver, properties, body):
    self.MESSAGE_WORKER.get_msg_from_mq(msg=body)

def get_msg_from_mq(msg)
	pass

消费这部分
以收到物理链路up为例,当探针收到真实路由器的keepalive报文,探针会认为链路已修好,此时会给rabbitmq发送message,通过type来区分收到的类型,作相应处理

    def reconnect(self, timestamp):
        send_to_channel_msg = {
                    'agent_id': '%s:%s' % ("1.1.1.1", "5412"),
                    'type': 4,
                    'msg': None
                }
                self.factory.channel.send_message(
                    exchange='', routing_key=self.factory.peer_addr, message=send_to_channel_msg)

执行后查看队列,记下队列名字与队列中所含消息的数量

#重启rabbitmq

systemctl restart rabbitmq-server

#重启完毕后再次查看

rabbitmqctl list_queues
Listing queues ...

#队列以及消息并未消失

还可以通过可视化界面来查看,以下是安装步骤

yum -y install epel-release
yum -y update
yum -y install erlang socat
wget https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.1/rabbitmq-server-3.6.1-1.noarch.rpm
rpm --import https://www.rabbitmq.com/rabbitmq-release-signing-key.asc
rpm -Uvh rabbitmq-server-3.6.1-1.noarch.rpm
rm -rf rabbitmq-server-3.6.1-1.noarch.rpm

systemctl start rabbitmq-server
systemctl enable rabbitmq-server


firewall-cmd --zone=public --permanent --add-port=15672/tcp
firewall-cmd --zone=public --permanent --add-port=5671-5672/tcp
firewall-cmd --reload
rabbitmqctl add_user root root  #添加用户名密码,默认是guest/guest

此时打开浏览器输入:127.0.0.1:15672就可以看到登录界面,输入之前设置的密码即可登录查看收到message

注意,当rabbitmq收到message分给consumer很快会被消耗,所以一般情况下看到的都是空的,若就是想看message是否被收到,建议stop consumer进程

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值