• 3.rabbitmq 发布/订阅


    1. 发布者

    #coding:utf8
    
    import pika
    import json
    import sys
    
    message = ''.join(sys.argv[1:]) or "hello word"
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
                   'localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='logs', exchange_type='fanout')
    # 创建交换机
    
    
    channel.basic_publish(exchange='logs',
        routing_key='',
        body=message)
    print " [x] Sent 'Hello World!'"
    
    connection.close()

    2. 订阅者

    # coding:utf8
    
    import pika
    import MySQLdb
    import time
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        'localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='logs',exchange_type='fanout')
    
    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue
    
    channel.queue_bind(exchange='logs',queue=queue_name)
    
    def callback(ch, method, properties, body):
        print("[x] received %r" % body)
        time.sleep(5)
        print("done")
        # ch.basic_ack(delivery_tag=method.delivery_tag) # ack 消息成功确认
    
    channel.basic_qos(prefetch_count=1)#公平分派
    channel.basic_consume(callback,
                          queue=queue_name,
                          no_ack=True)
    print("waiting for messages")
    channel.start_consuming()
  • 相关阅读:
    (二)扩展原理:【2】BeanDefinitionRegistryPostProcessor
    寒假学习日报3
    寒假学习日报6
    寒假学习日报8
    寒假学习日报9
    寒假学习日报7
    寒假学习日报1
    寒假学习日报4
    构建之法阅读笔记1
    寒假学习日报2
  • 原文地址:https://www.cnblogs.com/myvic/p/9685148.html
Copyright © 2020-2023  润新知