rabbitmq 连接被拒绝:celery -兔MQ

xcitsw88  于 2022-11-08  发布在  RabbitMQ
关注(0)|答案(1)|浏览(273)

我正在用FastAPI集成celery 。我正在使用rabbitmq作为celery 的代理。当我向celery 提交任务时,我得到这个错误:“kombu.异常.操作错误:[Errno 111]连接被拒绝”。我不明白也许是由于与rabbitmq的连接,但当我启动celery 工人,它没有给出任何连接错误,但在任务提交时。以下是我的代码:main.py

from fastapi import FastAPI
from scraper import crawl_data
from task import sample_task

app = FastAPI()

@app.get("/test")
def test():
    data = sample_task.delay()
    return {'MESSAGE': 'DONE'}

task.py

from celery_config import app
import time

@app.task
def sample_task():
    for i in range(1, 10):
        time.sleep(10)
    print("DONE TASK")

celery _配置.py

from celery import Celery

app = Celery('celery_tutorial',
             broker="amqp://guest:guest@localhost:5672//",
             include=['task'])

docker-compose.yml

version: "3.9"

services:
  main_app:
    build:
      context: .
      dockerfile: fastapi.Dockerfile
    command: uvicorn main:app --host 0.0.0.0 --reload
    ports:
      - "8000:8000"
  rabbitmq:
    image: rabbitmq:3.8-management-alpine
    ports:
      - 15673:15672

# celery_worker:

# build:

# context: .

# dockerfile: fastapi.Dockerfile

# command: celery -A celery worker --loglevel=info

# depends_on:

# - rabbitmq

# - main_app

    stdin_open: true

我用docker compose启动FastAPI服务器和rabbitmq,用以下命令启动celery worker:

celery -A celery_config worker --loglevel=info
f87krz0w

f87krz0w1#

假设您的celery_config.pymain_app容器中运行,则代理的主机应该是rabbitmq(服务名称)而不是localhost:

app = Celery('celery_tutorial',
             broker="amqp://guest:guest@rabbitmq:5672/vhost",
             include=['task'])

编辑

您似乎没有设置相关的环境变量:

rabbitmq:
    image: rabbitmq:3.8-management-alpine
    ports:
      - 15673:15672
    environment:
      - RABBITMQ_DEFAULT_VHOST=vhost
      - RABBITMQ_DEFAULT_USER=guest
      - RABBITMQ_DEFAULT_PASS=guest

请确保您添加了它们,请参见我答案here

相关问题