zoukankan      html  css  js  c++  java
  • RabbitMQ Hello篇

    生产者:

    #!/usr/bin/env python
    #coding:utf-8
    
    import pika
    #连接到服务上的broker
    SERVER_IP = "106.2.111.53"
    PORT = 5672
    credentials = pika.PlainCredentials("admin", "admin")
    parameters = pika.ConnectionParameters(SERVER_IP, PORT, '/', credentials)
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    
    '''
    新建队列(hello)
        如果我们向不在的队列发送消息会被rabbitmq丢弃
    '''
    channel.queue_declare(queue='hello')
    
    '''
    消息通过exchange发送给队列(消息不会直接发送给队列)
    一个空字符串标识的默认exchange, 允许我们精确指定消息应该发送到那个队列
    队列名字通过routing_key参数来指定
    '''
    channel.basic_publish(exchange='', routing_key="hello", body="Hello,RabbitMQ")
    print("[x]Productor send 'Hello RabbitMQ'")
    connection.close()

    消费者:

    #!/usr/bin/env python
    #coding:utf-8
    
    import pika
    
    SERVER_IP = "106.2.111.53"
    PORT = 5672
    credentials = pika.PlainCredentials("admin", "admin")
    parameters = pika.ConnectionParameters(SERVER_IP, PORT, '/', credentials)
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    #确保队列存在,多次执行,只有一个队列被创建
    channel.queue_declare(queue="hello")
    
    def callback(ch, method, properties, body):
        print("[x]Customer Received %r" %body)
    
    #从队列hello中接收消息--队列必须存在
    channel.basic_consume(callback, queue="hello", no_ack=True)
    print("[*]Waiting for messages. To exit press Ctrl+C")
    #进入无限循环,等待数据,并在需要的时候运行callbacks
    channel.start_consuming()

    eg:生产者循环1-100 发送消息,启动两个消费者,如下图

  • 相关阅读:
    BZOJ 1050 旅行
    BZOJ 1040 骑士
    BZOJ 1038 瞭望塔
    BZOJ 1037 生日聚会
    BZOJ 1823 满汉全席
    BZOJ 3091 城市旅行
    CF702E Analysis of Pathes in Functional Graph
    Luogu 2154 [SDOI2009]虔诚的墓主人
    Luogu 1268 树的重量
    Luogu 4867 Gty的二逼妹子序列
  • 原文地址:https://www.cnblogs.com/jachin/p/5503278.html
Copyright © 2011-2022 走看看