我的目标是有几个容器使用rabbitmq消息相互交互(rabbitmq服务器在单独的容器中),因此需要编写一个rabbit.py文件。
class Rabbit:
host = 'rabbitmq-host'
userid = 'test'
password = 'test'
class Consumer(Rabbit):
def __init__(self, exchange_name):
self.exchange_name = exchange_name
self.connection = None
try:
credentials = pika.PlainCredentials(self.userid, self.password)
params = pika.ConnectionParameters(self.host, 5672, '/', credentials)
self.connection = pika.BlockingConnection(params)
except Exception as ex:
print(ex)
if self.connection is not None and self.connection.is_open:
self.connection.close()
raise ex
self.channel = self.connection.channel()
证书测试:测试存在,我重新检查了。
然后从另一个文件(main.py)创建了消费者(Consumer)。
c = Consumer('media')
docker-compose.yml
version: '3'
services:
rabbitmq-server:
image: "rabbitmq:3-management"
hostname: "rabbitmq-host"
environment:
RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG"
RABBITMQ_DEFAULT_USER: "test"
RABBITMQ_DEFAULT_PASS: "test"
RABBITMQ_DEFAULT_VHOST: "/"
ports:
- "15672:15672"
- "5672:5672"
labels:
NAME: "rabbitmq1"
info-getter:
build: ./info-getter
depends_on:
- rabbitmq-server
tty: true
ports:
- "3000:3000"
在测试时,我在容器中运行rabbitmq服务器,但应用程序来自本地机器,一切正常,但当我执行'docker-compose up'时,出现以下异常:
info-getter_1 |
info-getter_1 | Traceback (most recent call last):
info-getter_1 | File "main.py", line 10, in <module>
info-getter_1 | c = Consumer('media')
info-getter_1 | File "libs/rabbit.py", line 27, in __init__
info-getter_1 | raise ex
info-getter_1 | File "libs/rabbit.py", line 22, in __init__
info-getter_1 | self.connection = pika.BlockingConnection(params)
info-getter_1 | File "/usr/local/lib/python3.6/site-packages/pika/adapters/blocking_connection.py", line 360, in __init__
info-getter_1 | self._impl = self._create_connection(parameters, _impl_class)
info-getter_1 | File "/usr/local/lib/python3.6/site-packages/pika/adapters/blocking_connection.py", line 451, in _create_connection
info-getter_1 | raise self._reap_last_connection_workflow_error(error)
info-getter_1 | pika.exceptions.AMQPConnectionError
services_info-getter_1 exited with code 1
我错在哪里?
此外,我想补充的是,即使我已经指定了 'depends_on',但在运行 'docker-compose up' 后,info-getter 日志会出现在 rabbitmq-server 日志之前。