channel rabbitmq 配置_rabbitmq配置与简单使用

一、在windos中安装配置rabbitmq

本次使用rabbitmq作为broker,不设后端backend

rabbitmq在4.0之后不支持windows使用,可以下载老版本的在本地windows使用。

http://erlang.org/download/otp_win64_17.3.exe  先下载安装erlang语言

部分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 -*-

importpikaimporttime

hostname= 'localhost'parameters=pika.ConnectionParameters(hostname)

connection=pika.BlockingConnection(parameters)#创建通道

channel =connection.channel()

channel.queue_declare(queue='task_queue1',durable=True)defcallback(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 -*-

importpikaimportrandom

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 -*-

importpikaimportrandom

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()

可以看到轮流接受传收到的信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值