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
  • 相关阅读:
    06 is和==的区别 encode()编码 decode()解码
    05 dic的增删改查 字典的嵌套 考试题dic.get()的相关使用
    03 编码 int ,bool,str的常用操作 主要讲str
    01 基本数据类型 变量 if语句
    04 列表的增删改查 常用方法 元祖 range
    02 while循环 格式化输出 运算符
    多校2 Harmonious Army hdu6598 网络流
    P3159 [CQOI2012]交换棋子 网络流
    P2172 [国家集训队]部落战争 最大流
    P2402 奶牛隐藏 网络流
  • 原文地址:https://www.cnblogs.com/GodLv/p/9953297.html
Copyright © 2011-2022 走看看