• 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 发送消息,启动两个消费者,如下图

  • 相关阅读:
    C语言指针和数组
    C语言malloc、calloc函数
    33、二叉树的后序遍历序列
    进程、线程、协程
    8、字符串转整数
    51、数组中的逆序对
    49、丑数
    19、正则表达式匹配
    32、从上到下打印二叉树
    leetcode5:最长回文子串
  • 原文地址:https://www.cnblogs.com/jachin/p/5503278.html
Copyright © 2020-2023  润新知