消息中间件—RabbitMQ
应用场景:异步
开发语言 :erlang
端口号:
4369 – erlang发现口
5672 --client端通信口
15672 – 管理界面ui端口
25672 – server间内部通信口
一对一的发送
#############声明send函数#######################################
import pika
credentials = pika.PlainCredentials('test','test')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost',credentials=credentials))
channel = connection.channel() #声明队列向其发送消息
channel.queue_declare(queue='hello') #声明队列
channel.basic_publish(exechange='',
routing_key='hello',
body='Hello,World!')
print("Send 'Hello World!'")
connection.close()
#################################################################
#############声明receive函数#######################################
import pika
credentials = pika.PlainCredentials('test','test')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost',credentials=credentials))
channel = connection.channel() #声明队列
channel.queue_declare(queue='hello') #声明队列向其发消息
def callback(ch, method, properties, body): #定义callback函数
print("[x] Received %r" % ch, method, properties, body)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
print('[*] Waiting for messages.To exit press CTRL+C')
channel.start_consuming() #开始消费
#################################################################
声明一个队列,然后往其中发消息,然后我们准备两个消费者来接收,默认情况的接收顺序是依次公平接收。
rabbitmq循环调度,将消息循环发送给不同的消费者,如:消息1,3,5发送给消费者1;消息2,4,6发送给消费者2。
no_ack参数
ack参数是客户端在消费完消息之后向客户端返回的一个状态,默认我们要开启
消费者处理任务结束后,会给服务器一个反馈。服务器接收到反馈后就会删除掉任务,如果服务器没有接收到反馈,就会从其他地方拿到任务放回队列,让其它用户接收。
delivery_mode参数 —消息持久化
durable参数 —队列持久化
消息持久化,将消息写入硬盘中。 RabbitMQ不允许你重新定义一个已经存在、但属性不同的queue。需要标记消息为持久化的 - 要通过设置 delivery_mode 属性为 2来实现。
channel.queue_declare(queue='task_queue', durable=True) #创建一个新队列task_queue,设置队列持久化,注意不要跟已存在的队列重名,否则有报错
channel.basic_publish(exchange='',
14 routing_key='worker',#写明将消息发送给队列worker
15 body=message, #要发送的消息
16 properties=pika.BasicProperties(delivery_mode=2,)#设置消息持久化,将要发送的消息的属性标记为2,表示该消息要持久化
17 )
完整代码示例:
生产者:
import pika
import sys
username = 'wt' #指定远程rabbitmq的用户名密码
pwd = '111111'
user_pwd = pika.PlainCredentials(username, pwd)
s_conn = pika.BlockingConnection(pika.ConnectionParameters('192.168.1.240', credentials=user_pwd))#创建连接
channel = s_conn