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 小时前
Docker:3、在VSCode上安装并运行python程序或JavaScript程序
运维·vscode·python·docker·容器·js
paterWang2 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑2 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
神秘_博士3 小时前
自制AirTag,支持安卓/鸿蒙/PC/Home Assistant,无需拥有iPhone
arm开发·python·物联网·flutter·docker·gitee
Moutai码农4 小时前
机器学习-生命周期
人工智能·python·机器学习·数据挖掘
小白教程5 小时前
python学习笔记,python处理 Excel、Word、PPT 以及邮件自动化办公
python·python学习·python安装
武陵悭臾5 小时前
网络爬虫学习:借助DeepSeek完善爬虫软件,实现模拟鼠标右键点击,将链接另存为本地文件
python·selenium·网络爬虫·pyautogui·deepseek·鼠标右键模拟·保存链接为htm
一條狗5 小时前
20250219 隨筆 [特殊字符] 查看短鏈的實現方式與解決方案優化
rabbitmq·冗餘雙寫
代码猪猪傻瓜coding6 小时前
关于 形状信息提取的说明
人工智能·python·深度学习
码界筑梦坊7 小时前
基于Flask的第七次人口普查数据分析系统的设计与实现
后端·python·信息可视化·flask·毕业设计