标签:
本篇主要内容:
redis发布与订阅补充
python操作rabbitMQ
如下一个简单的监控模型,通过这个模式所有的收听者都能收听到一份数据。
用代码来实现一个redis的订阅者何消费者。
定义一个类:
import redis class Redis_helper(): def __init__(self): self.__conn = redis.Redis(host=‘192.168.11.87‘) #创建一个连接 def pub(self, mes, chan): #发布方法 self.__conn.publish(chan, mes) return True def sub(self, chan): #订阅方法 pub = self.__conn.pubsub() pub.subscribe(chan) pub.parse_response() return pub
发布者代码
import class_redishelper import time obj = class_redishelper.Redis_helper() num = 1 while True: time.sleep(1) obj.pub(num,‘fm111.7‘) num += 1
订阅者代码
import class_redishelper while True: obj = class_redishelper.Redis_helper() data = obj.sub(‘fm111.7‘) print(data.parse_response())
RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。
MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。
安装配置epel源 $ rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm 安装erlang $ yum -y install erlang 安装RabbitMQ $ yum -y install rabbitmq-server
service rabbitmq-server start/stop
pip install pika or easy_install pika or 源码 https://pypi.python.org/pypi/pika
在上篇中有提到过python的队列queue,也通过这个queue实现了一个简单的生产者和消费者的模型,这个所说的队列,其实是只针对了内存中的一个queue对象。然而RabbitMQ并不是这样,而是单独利用单独的服务器来维护这个队列,这个队列是由RabbitMQ来维护的。
如下利用RabbitMQ来实现一个简单的生产者,消费者模型。
import pika # ######################### 生产者 ######################### connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘192.168.11.135‘)) channel = connection.channel() channel.queue_declare(queue=‘hello‘) channel.basic_publish(exchange=‘‘, routing_key=‘hello‘, body=‘Hello World!--zhaowencheng‘) print(" [x] Sent ‘Hello World!‘") connection.close()
import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘192.168.11.135‘)) channel = connection.channel() channel.queue_declare(queue=‘hello‘) def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume(callback, queue=‘hello‘, no_ack=True) print(‘ [*] Waiting for messages. To exit press CTRL+C‘) channel.start_consuming()
acknowledgment 消息不丢失--针对消费者端的确保方式,获取后给服务器返回一个确认值,如果没有确认值,那么服务端就认为没有消费完,在把刚才的数据重新放到队列里
代码如下:
import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘10.211.55.4‘)) channel = connection.channel() channel.queue_declare(queue=‘hello‘) def callback(ch, method, properties, body): print(" [x] Received %r" % body) import time time.sleep(10) print ‘ok‘ ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_consume(callback, queue=‘hello‘, no_ack=False) print(‘ [*] Waiting for messages. To exit press CTRL+C‘) channel.start_consuming() #消费者
durable 消息不丢失,针对服务端做标记指定本消息做类似固化的操作,保证在挂掉或者重启时能够再加载
如下代码即在服务端保障,又在client端保障:
#!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host=‘10.211.55.4‘)) channel = connection.channel() # make message persistent channel.queue_declare(queue=‘hello‘, durable=True) channel.basic_publish(exchange=‘‘, routing_key=‘hello‘, body=‘Hello World!‘, properties=pika.BasicProperties( delivery_mode=2, # make message persistent )) print(" [x] Sent ‘Hello World!‘") connection.close() #生产者 ################## #!/usr/bin/env python # -*- coding:utf-8 -*- import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host=‘10.211.55.4‘)) channel = connection.channel() # make message persistent channel.queue_declare(queue=‘hello‘, durable=True) def callback(ch, method, properties, body): print(" [x] Received %r" % body) import time time.sleep(10) print ‘ok‘ ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_consume(callback, queue=‘hello‘, no_ack=False) print(‘ [*] Waiting for messages. To exit press CTRL+C‘) channel.start_consuming() 消费者
默认消息队列里的数据是按照顺序被消费者拿走,例如:消费者1 去队列中获取 奇数 序列的任务,消费者1去队列中获取 偶数 序列的任务。
这样消费者只会获取自己对应的数据,但是由于获取后处理的速度不同会造成处理的不同不性,
channel.basic_qos(prefetch_count=1) 表示谁来谁取,不再按照奇偶数排列,按照顺序依此往下取:
#!/usr/bin/env python # -*- coding:utf-8 -*- import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host=‘10.211.55.4‘)) channel = connection.channel() # make message persistent channel.queue_declare(queue=‘hello‘) def callback(ch, method, properties, body): print(" [x] Received %r" % body) import time time.sleep(10) print ‘ok‘ ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue=‘hello‘, no_ack=False) print(‘ [*] Waiting for messages. To exit press CTRL+C‘) channel.start_consuming() 消费者
发布者讲消息发布到 指定的exchange中,然后此exchange所绑定的所有的队列中都可以存在此消息,此时不同的订阅者都可以读取订阅了。
发布订阅和简单的消息队列区别在于,发布订阅会将消息发送给所有的订阅者,而消息队列中的数据被消费一次便消失。所以,RabbitMQ实现发布和订阅时,会为每一个订阅者创建一个队列,而发布者发布消息时,会将消息放置在所有相关队列中。
exchange type = fanout:
##ex###########发布端 !/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘192.168.11.135‘)) #创建一个链接 channel = connection.channel() #创建一个频道用来操作链接 channel.exchange_declare(exchange=‘logs‘, type=‘fanout‘) #定义一个队列(如果订阅者已经创建完了那么这里可有可无) message = "2222222-" #定义一个信息 channel.basic_publish(exchange=‘logs‘, #发送数据 指定exchange的名字 routing_key=‘‘, body=message) print(" [x] Sent %r" % message) connection.close() #关闭 ##############
####订阅端--ex import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host=‘192.168.11.135‘)) #创建一个连接 channel = connection.channel() #创建频道 channel.exchange_declare(exchange=‘logs‘,type=‘fanout‘) #声明exchange result = channel.queue_declare(exclusive=True) # queue_name = result.method.queue #随机创建一个队列 channel.queue_bind(exchange=‘logs‘,queue=queue_name) #绑定上面的随记队列 print(‘ [*] Waiting for logs. To exit press CTRL+C‘) def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume(callback, queue=queue_name, no_ack=True) channel.start_consuming()
关键字发送 -- exchange类型为direct
exchange type = direct
之前事例,发送消息时明确指定某个队列并向其中发送消息,RabbitMQ还支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,exchange根据 关键字 判定应该将数据发送至指定队列。
#关键字方式。######发布端 #!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘192.168.11.135‘)) channel = connection.channel() channel.exchange_declare(exchange=‘direct_logs_1‘, type=‘direct‘) severity = "info" message = ‘ ‘.join(sys.argv[2:]) or ‘Hello World!‘ channel.basic_publish(exchange=‘direct_logs_1‘, routing_key=severity, body=message) print(" [x] Sent %r:%r" % (severity, message)) connection.close()
########发布端## #关键字方式 #!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘192.168.11.135‘)) channel = connection.channel() channel.exchange_declare(exchange=‘direct_logs_1‘, type=‘direct‘) result = channel.queue_declare(exclusive=True) queue_name = result.method.queue severities = ["error","info"] for severity in severities: channel.queue_bind(exchange=‘direct_logs_1‘, #绑定关键字。 queue=queue_name, routing_key=severity) print(‘ [*] Waiting for logs. To exit press CTRL+C‘) def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume(callback, queue=queue_name, no_ack=True) channel.start_consuming()
模糊匹配 -- exchange类型为topic
在topic类型下,可以让队列绑定几个模糊的关键字,之后发送者将数据发送到exchange,exchange将传入”路由值“和 ”关键字“进行匹配,匹配成功,则将数据发送到指定队列。
#####订阅者 #!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘localhost‘)) channel = connection.channel() channel.exchange_declare(exchange=‘topic_logs‘, type=‘topic‘) result = channel.queue_declare(exclusive=True) queue_name = result.method.queue binding_keys = sys.argv[1:] if not binding_keys: sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0]) sys.exit(1) for binding_key in binding_keys: channel.queue_bind(exchange=‘topic_logs‘, queue=queue_name, routing_key=binding_key) print(‘ [*] Waiting for logs. To exit press CTRL+C‘) def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume(callback, queue=queue_name, no_ack=True) channel.start_consuming() #消费者
#发布端 #!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host=‘localhost‘)) channel = connection.channel() channel.exchange_declare(exchange=‘topic_logs‘, type=‘topic‘) routing_key = sys.argv[1] if len(sys.argv) > 1 else ‘anonymous.info‘ message = ‘ ‘.join(sys.argv[2:]) or ‘Hello World!‘ channel.basic_publish(exchange=‘topic_logs‘, routing_key=routing_key, body=message) print(" [x] Sent %r:%r" % (routing_key, message)) connection.close() 生产者
文成小盆友python-num12 Redis发布与订阅补充,python操作rabbitMQ
标签:
原文地址:http://www.cnblogs.com/wenchengxiaopenyou/p/5700630.html