python的rabbitmq简单使用

rabbitmq在Python被封装的是pika模块

使用的话  pip  install pika

消息头设置

# -*- coding: utf-8 -*-


import pika
import random

uuser="user"
upass="pass"
uip="192.168.7.7"
uport="5678"
routing_key="hello,queue"
#定义发送端参数


credentials = pika.PlainCredentials(uuser, upass)
#创建证书,为Rabbitmq服务端的用户名和密码


connection = pika.BlockingConnection(pika.ConnectionParameters(uip,uport,'/',credentials))
#创建连接,参数为Rabbitmq服务端的IP、端口、虚拟主机和证书


channel = connection.channel()
#c创建通道


channel.confirm_delivery()
#定义消息发送为确认模式


header= {
                  "a",
                  "b",
                  "c",
                  "c",
                  "d",
                  "e",
        }
#设置消息头


body="abcdefg"
#设置消息体


channel.basic_publish(exchange=exchange,
                                 routing_key=routing_key,
                                 body=body,
                                 properties=pika.BasicProperties(content_type='application/json',
                                                                 headers=header,
                                                                 delivery_mode=2),
                                 mandatory=True)
#消息发送成功

channel.close()
connection.close()
#发完关闭

接收端

接收端
# -*- coding: utf-8 -*-

import pika

queue="hello,queue"
uuser="user"
upass="pass"
uip="192.168.7.7"
uport="5678"
#定义发送端参数


credentials = pika.PlainCredentials(uuser, upass)
#创建证书,为Rabbitmq服务端的用户名和密码


connection = pika.BlockingConnection(pika.ConnectionParameters(uip,uport,'/',credentials))
#创建连接,参数为Rabbitmq服务端的IP、端口、虚拟主机和证书


channel = connection.channel()
#c创建通道


channel.basic_consume(self.callback, queue=queue)
#设置接受端


# 定义接收消息的回调函数 ,参数为通道、回调函数标识、消息属性、消息体
def callback(self,cha, method, properties, body):
    cha="通道"
    method="消息队列"
    properties="消息头"
    body="消息体"

    method.routing_key#队列名

    properties.headers[0]#消息头的a
    properties.headers[1]  # 消息头的b

    body="abcde"
    #以上接收参数的定义以及使用,下面的函数根据自己的需求来写

不过多解释了,以上只是一个参考,具体的使用根据自己的情况去详细设置使用

猜你喜欢

转载自blog.csdn.net/zlx_csdn/article/details/81155519