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
成功