• 周三. 6月 29th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

RabbitMQ之入门

admin

11月 28, 2021

生成者:

#coding:utf-8
import sys

import pika

credentials=pika.PlainCredentials("guest","guest")

#获取信道
conn_params=pika.ConnectionParameters("192.168.30.252",credentials=credentials)
conn_broker=pika.BlockingConnection(conn_params)
channel=conn_broker.channel()

#声明交换器
'''
callback=None,
exchange=None,  #交换器名称
exchange_type='direct', #交换器的类型
passive=False, #校验是否存在
durable=False, #是否持久化
auto_delete=False,#最后一个订阅后是否删除
internal=False,
nowait=False,
arguments=None,
type=None
'''
channel.exchange_declare(exchange="hello-exchange",type="direct",passive=False,durable=True,auto_delete=False)

#创建文本消息
msg=sys.argv[1]
msg_props=pika.BasicProperties()
msg_props.content_type='text/plain'

#发布消息
channel.basic_publish(body=msg,exchange="hello-exchange",properties=msg_props,routing_key="hola")

  

消费者:

#coding:utf-8
__author__ = 'similarface'
import pika
#建立到代理服务器的连接
credentials=pika.PlainCredentials('guest','guest')
conn_params=pika.ConnectionParameters("localhost",credentials=credentials)
conn_broker=pika.BlockingConnection(conn_params)

#获取信道
channel=conn_broker.channel()

#声明交换器
channel.exchange_declare(exchange="hello-exchange",type="direct",passive=False
                         ,durable=True,auto_delete=False)

#声明队列
channel.queue_declare(queue="hello-queue")

#通过键hola 将队列和交换器绑定
channel.queue_bind(queue="hello-queue",exchange="hello-exchange",routing_key="hola")

#用于处理传入消息的函数
def msg_consumer(channel,method,header,body):
    #消息确认
    channel.basic_ack(delivery_tag=method.delivery_tag)

    if body=="quit":
        #停止消费并退出
        channel.basic_cancel(consumer_tag="hello-consumer")
        channel.stop_consuming()
    else:
        print(body)
    return
#订阅消费者
channel.basic_consume(msg_consumer,queue="hello-queue",consumer_tag="hello-consumer")
#开始消费
channel.start_consuming()

发表评论

您的电子邮箱地址不会被公开。