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

成功

相关推荐
zhangfeng11335 分钟前
PowerShell 中不支持激活你选中的 Python 虚拟环境,建议切换到命令提示符(Command Prompt)
开发语言·python·prompt
qh0526wy9 分钟前
WINDOWS BAT 开机登录后自动启动
windows·python
程序员哈基耄18 分钟前
浏览器文件格式转换工具:简单、安全、高效的文本与数据处理助手
python·安全·数据挖掘
FL162386312927 分钟前
基于yolov8的无人机视角夜间车辆检测识别系统python源码+onnx模型+评估指标曲线+精美GUI界面
python·yolo·无人机
GIS之路32 分钟前
GDAL 实现影像裁剪
前端·python·arcgis·信息可视化
大飞记Python1 小时前
代码级教程|用Playwright实现Web自动化测试:从零到录制生成脚本
自动化测试·python·selenium·playwright
_WndProc1 小时前
【Python】方程计算器
开发语言·python
我的offer在哪里1 小时前
技术实战:用 Python 脚本高效采集与分析手机操作日志
开发语言·python·智能手机
智航GIS1 小时前
11.18 自定义Pandas扩展开发指南:打造你的专属数据分析武器库
python·数据分析·pandas
AI_56781 小时前
测试用例“标准化”:TestRail实战技巧,从“用例编写”到“测试报告生成”
java·python·测试用例·testrail