zoukankan      html  css  js  c++  java
  • python采用pika库使用rabbitmq(二)

    Pika是用于Python的RabbitMQ(AMQP-0-9-1)客户端库,官方文档地址:https://pypi.org/project/pika/

    工作模式:其中P表示produce,生产者的意思,也可以称为发送者,实例中表现为send.py;C表示consumer,消费者的意思,也可以称为接收者,实例中表现为receive.py;中间红色的表示队列的意思,实例中表现为hello队列。

     1 import pika
     2 
     3 
     4 credentials = pika.PlainCredentials('admin', 'passwd')
     5 connection = pika.BlockingConnection(pika.ConnectionParameters(
     6     'ip',credentials=credentials))
     7 
     8 
     9 
    10 channel = connection.channel() #建立了rabbit 协议的通道
    11 
    12 # 声明queue,
    13 channel.queue_declare(queue='hello')
    14 
    15 # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
    16 channel.basic_publish(exchange='',
    17                       routing_key='hello',
    18                       body='Hello World!')
    19 '''
    20         exchange表示交换器,能精确指定消息应该发送到哪个队列
    21         routing_key设置为队列的名称
    22         body就是发送的内容
    23 '''
    24 print(" [x] Sent 'Hello World!'")
    25 connection.close()
    send.py

    可以使用

    rabbitmqctl list_queues命令查看队列

     1 import pika
     2 import time
     3 
     4 credentials = pika.PlainCredentials('admin', 'passwd')
     5 connection = pika.BlockingConnection(pika.ConnectionParameters(
     6     'ip',credentials=credentials))
     7 
     8 channel = connection.channel()
     9 
    10 channel.queue_declare(queue='hello')
    11 
    12 
    13 def callback(ch, method, properties, body):
    14 
    15     print("received msg...start processing....",body)
    16     time.sleep(20)
    17     print(" [x] msg process done....",body)
    18 
    19 
    20 channel.basic_consume(callback,
    21                       queue='hello',
    22                       no_ack=True)
    23 
    24 print(' [*] Waiting for messages. To exit press CTRL+C')
    25 channel.start_consuming()
    receive.py
  • 相关阅读:
    App自动化01-Appium概述
    App绕过SSL Pinning机制抓取Https请求
    手机大厂必备测试技能-GMS 认证
    手机大厂必备测试技能-CTS 兼容测试
    一文搞定web自动化环境常见问题
    Airtest-UI 自动化集大成者
    shell三剑客之sed
    shell三剑客之grep
    二月主题读书整理——元技能系列
    深度学习目标检测综述推荐之 Xiaogang Wang ISBA 2015
  • 原文地址:https://www.cnblogs.com/GodLv/p/9953297.html
Copyright © 2011-2022 走看看