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

成功

相关推荐
如竟没有火炬7 小时前
四数相加贰——哈希表
数据结构·python·算法·leetcode·散列表
背心2块钱包邮8 小时前
第9节——部分分式积分(Partial Fraction Decomposition)
人工智能·python·算法·机器学习·matplotlib
木盏8 小时前
三维高斯的分裂
开发语言·python
a程序小傲8 小时前
京东Java面试被问:ZGC的染色指针如何实现?内存屏障如何处理?
java·后端·python·面试
大连好光景8 小时前
批量匿名数据重识别(debug记录)
开发语言·python
暴风鱼划水8 小时前
算法题(Python)哈希表 | 2.两个数组的交集
python·算法·哈希表
清水白石0088 小时前
《深入 Celery:用 Python 构建高可用任务队列的实战指南》
开发语言·python
BoBoZz199 小时前
Hello 隐式建模
python·vtk·图形渲染·图形处理
副露のmagic9 小时前
更弱智的算法学习day 10
python·学习·算法
javpy9 小时前
AI生成 Python小游戏 怪物防御战???
人工智能·python·pygame