使用RabbitMQ实现带权限的Routing

一、RabbitMQ的安装(官网安装教程

#ubuntu安装方式,如果出错,按照终端提示方式进行安装
sudo dpkg -i rabbitmq-server_3.3.5-1_all.deb

检查rabbitmq默认服务端口5672是否已监听

netstat -ntlp | grep LISTEN

二、创建用户、虚拟主机、配置权限

sudo rabbitmqctl add_vhost test
sudo rabbitmqctl add_user test 123456
sudo rabbitmqctl set_permissions -p test test ".*" ".*" ".*"


三、简单Routing程序

rabbitmq.py

#-*-coding:utf-8-*-
#!/usr/bin/env python
#rabbitmq.py

import pika
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

mq = {
	'host': '127.0.0.1',
	'port': 5672,
	'user': 'test',
	'pwd': '123456',
	'virt': 'test',
	'exchange': 'securityte',
	'exchange_type': 'direct',
}

class MQRouting():
	"""rabbitmq操作类,广播消息到所有队列,各队列进行消息筛选"""
	def __init__(self):
		credentials = pika.PlainCredentials(mq['user'], mq['pwd'])
		self.conn = pika.BlockingConnection(pika.ConnectionParameters(mq['host'], mq['port'], mq['virt'], credentials))
		self.channel = self.conn.channel()
		self.channel.exchange_declare(exchange=mq['exchange'], type=mq['exchange_type'])
		logger.info('Rabbitmq连接已建立,host={}, port={}'.format(mq['host'], mq['port']))

	def public(self, routing_key, msg):
		"""发布消息"""
		self.channel.basic_publish(
			exchange = mq['exchange'],
			routing_key = routing_key,
			body=msg,
			properties=pika.BasicProperties(
				delivery_mode = 2, # make message persistent
			)
		)
		logger.info('消息已发布:{}:{}'.format(routing_key,msg))

	def consume(self, routing_key):
		"""接收消息"""
		def callback(ch, method, properties, body):
			print " [x] Received %r" % (body,)
		self.channel.queue_declare(queue=routing_key)
		self.channel.queue_bind(exchange=mq['exchange'], queue=routing_key, routing_key=routing_key)
		self.channel.basic_consume(callback, queue=routing_key, no_ack=True)
		self.channel.start_consuming()

	def close(self):
		if self.channel: self.channel.close()
		if self.conn: self.conn.close()


if __name__ == '__main__':
	routing = MQRouting()
	routing.public('first','hello first!')
	routing.public('second','hello second!')


consume1.py

from rabbitmq import MQRouting

routing = MQRouting()
routing.consume('first')

consume2.py

from rabbitmq import MQRouting

routing = MQRouting()
routing.consume('second')


运行代码

python rabbitmq.py
python consume1.py
python consume2.py


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值