python生产者发消息到rabbitMq

python 复制代码
import pika


credentials = pika.PlainCredentials('zhanghao', 'mima')
connection = pika.BlockingConnection(pika.ConnectionParameters(
host="xxx", port=5672, credentials=credentials
))
channel = connection.channel()

channel.queue_declare(queue='dt_queue_gptsovits_ssml',durable=True)
channel.queue_declare(queue='dt_queue_gptsovits_ssml_dev', durable=True)
channel.basic_publish(exchange='',routing_key='dt_queue_gptsovits_ssml_dev',body="123")

这个就是代码,如果用接口的方式,声明队列要放在接口外面。初始化一次,调用的时候只发送消息,不创建新的套接字通道。, heartbeat=10 我把这个去掉了。有心跳的话,没有消息发过来,他会断开链接

下面是接口形式,就是请求接口,然后能发送消息。

发消息重新连接,不要保持长连接,连完发送就端口就行,只有消费者才需要长连接。

python 复制代码
import uvicorn as uvicorn
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
import pika
import json

app = FastAPI()
port = 9880
host = "0.0.0.0"



#---1声明队列
channel.queue_declare(queue='dt_queue_gptsovits_ssml',durable=True)
channel.queue_declare(queue='dt_queue_gptsovits_ssml_dev', durable=True)
@app.post("/send_mq_ssml")
async def send_mq_ssml(request: Request):

    json_post_raw = await request.json()
    print("接收到的参数是" + json.dumps(json_post_raw))
    rs = json_post_raw.get("rs")
    env = json_post_raw.get("env")
    credentials = pika.PlainCredentials('xxxx', 'xxxx')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
    host="xxxx", port=5672, credentials=credentials, heartbeat=10
    ))
    channel = connection.channel()
    if env=="prod":
        #发送正式
        channel.basic_publish(exchange='',
                              routing_key='dt_queue_gptsovits_ssml',
                              body=str(rs))
    else:
        print("队列发了测试中,消息是"+str(rs))
        # 发测试
        channel.basic_publish(exchange='',
                              routing_key='dt_queue_gptsovits_ssml_dev',
                              body=rs)
    connection.close()
    return "ok"

if __name__ == "__main__":
    uvicorn.run(app, host=host, port=port, workers=1)

看一下mq

成功

相关推荐
应用市场1 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
东方佑2 小时前
从字符串中提取重复子串的Python算法解析
windows·python·算法
Dfreedom.2 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生2 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
叶子丶苏3 小时前
第八节_PySide6基本窗口控件_按钮类控件(QAbstractButton)
python·pyqt
百锦再4 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven
Blossom.1184 小时前
把AI“刻”进玻璃:基于飞秒激光量子缺陷的随机数生成器与边缘安全实战
人工智能·python·单片机·深度学习·神经网络·安全·机器学习
Kratzdisteln5 小时前
【Python OOP Diary 1.1】题目二:简单计算器,改错与优化
python·面向对象编程
小白银子5 小时前
零基础从头教学Linux(Day 53)
linux·运维·python
skywalk81636 小时前
基于频域的数字盲水印blind-watermark
linux·开发语言·python