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

成功

相关推荐
久念祈4 小时前
C++ - 仿 RabbitMQ 实现消息队列--服务端核心模块实现(四)
分布式·rabbitmq
毛飞龙5 小时前
Python类(class)参数self的理解
python··self
魔尔助理顾问5 小时前
系统整理Python的循环语句和常用方法
开发语言·后端·python
颜颜yan_7 小时前
Python面向对象编程详解:从零开始掌握类的声明与使用
开发语言·redis·python
我的ID配享太庙呀8 小时前
Django 科普介绍:从入门到了解其核心魅力
数据库·后端·python·mysql·django·sqlite
@蓝莓果粒茶9 小时前
LeetCode第350题_两个数组的交集II
c++·python·学习·算法·leetcode·职场和发展·c#
FinAnalyzer9 小时前
如何在 InsCodeAI 上搭建并使用 Jupyter Notebook 环境?
ide·python·jupyter
java1234_小锋9 小时前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 微博文章数据可视化分析-文章分类下拉框实现
python·自然语言处理·flask
檀越剑指大厂9 小时前
【Python系列】Flask 应用中的主动垃圾回收
开发语言·python·flask
檀越剑指大厂9 小时前
【Python系列】使用 memory_profiler 诊断 Flask 应用内存问题
开发语言·python·flask