一、在windos中安装配置rabbitmq
本次使用rabbitmq作为broker,不设后端backend
rabbitmq在4.0之后不支持windows使用,可以下载老版本的在本地windows使用。
http://erlang.org/download/otp_win64_17.3.exe 先下载安装erlang语言
https://www.rabbitmq.com/download.html 再下载rabbitmq 我在本地下载的3.5.8版本
部分RabbitMQ版本可能与erlang语言版本不适配而导致不能使用
安装好后默认的http访问端口为15672
amqp端口为5672
默认用户名密码
guest guest
二、用docker启动rabbitmq
2.在docker中启动
docker run -d --hostname localhost --name myrabbit -p 15672:15672 -p 5672:5672 rabbitmq:3.6.15-management
启动带有web页面的rabbitmq
-d 后台进程运行
hostname RabbitMQ主机名称
name 容器名称
-p port:port 本地端口:容器端口
-p 15672:15672 http访问端口
-p 5672:5672 amqp访问端口
http只能用宿主ip+端口进行访问
ampq 可以用localhost和宿主ip都访问
默认用户名密码
guest guest
三、使用RabbitMQ
receive.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pika import time hostname = 'localhost' parameters = pika.ConnectionParameters(hostname) connection = pika.BlockingConnection(parameters) # 创建通道 channel = connection.channel() channel.queue_declare(queue='task_queue1',durable=True) def callback(ch, method, properties, body): print " [x] Received %r" % (body,) time.sleep(2) print " [x] Done" ch.basic_ack(delivery_tag=method.delivery_tag) # basic_qos设置prefetch_count=1,使得rabbitmq不会在同一时间给工作者分配多个任务, # 即只有工作者完成任务之后,才会再次接收到任务。 channel.basic_qos(prefetch_count=1) # 告诉rabbitmq使用callback来接收信息 channel.basic_consume('task_queue1', callback) # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理,按ctrl+c退出 print ' [*] Waiting for messages. To exit press CTRL+C' channel.start_consuming()
pycharm终端中启动 python receive.py
send1.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pika import random hostname = 'localhost' parameters = pika.ConnectionParameters(hostname) connection = pika.BlockingConnection(parameters) # 创建通道 channel = connection.channel() # 如果rabbitmq自身挂掉的话,那么任务会丢失。所以需要将任务持久化存储起来,声明持久化存储: channel.queue_declare(queue='task_queue1', durable=True) number = random.randint(1, 1000) message = 'hello world:%s' % number # 在发送任务的时候,用delivery_mode=2来标记任务为持久化存储: channel.basic_publish(exchange='', routing_key='task_queue1', body=message, properties=pika.BasicProperties( delivery_mode=2, )) print " [x] Sent %r" % (message,) connection.close()
send.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import pika import random hostname = 'localhost' parameters = pika.ConnectionParameters(hostname) connection = pika.BlockingConnection(parameters) # 创建通道 channel = connection.channel() # 声明hello队列,生产者消费者在相同队列 channel.queue_declare(queue='hello',durable=True) number = random.randint(1, 1000) body = 'hello world:%s' % number # 写明发送队列和指定队列 channel.basic_publish(exchange='', routing_key='hello',body=body,properties=pika.BasicProperties(delivery_mode=2)) print "[x] sent %s" % body connection.close()
可以看到轮流接受传收到的信息