在看RabbitMQ实战 高效部署分布式消息队列这本书的时候出现的问题。
把
channel.basic_consume(msg_consumer, queue="hello-queue", consumer_tag="hello-consumer")
改成
channel.basic_consume("hello-queue", msg_consumer, consumer_tag="hello-consumer")
就好了,哎 是源码里面参数的位置变了。
这个是抄自stackoverflow上的回答,虽然也没有什么用。
https://stackoverflow.com/questions/50404273/python-tutorial-code-from-rabbitmq-failing-to-run
I can't reproduce your error, but I want to be as concise as possible, when trying to.
At first I set up a rabbitmq server as docker container on my computer, not to pollute my system:
$ docker run -d --hostname localhost --name some-rabbit rabbitmq:3
Then I use inspect to find about the IPAddress my rabbitmq container is running actually:
$ docker inspect some-rabbit --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'
172.17.0.2
Next I use pipenv to create a virtual environment in python3 that contains at least pika and dependencies to follow the example:
$ mkdir example && cd example && pipenv --three install pika
Creating a virtualenv for this project…
Using /usr/bin/python3 (3.6.5) to create virtualenv…
Note, that you can also use python 2.7 here if you say pipenv --two
when installing pika.
Then jump into the environment using pipenv shell:
~/example$ pipenv shell
Spawning environment shell (/bin/bash). Use 'exit' to leave.
There I create the two files send.py
and receive.py
as proposed by the example documentation of pika, but I'll replace the localhost
by the docker containers IP from above:
$ cat send.py
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='172.17.0.2'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
And receive.py
:
$ cat receive.py
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='172.17.0.2'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
Having receive.py running in one terminal and running send.py in another works as expected:
$ python receive.py
[*] Waiting for messages. To exit press CTRL+C
$ python send.py
[x] Sent 'Hello World!'
$ python receive.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'Hello World!