消息队列:rabbitmq

MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。

应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。

消息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用(rpc)的技术。

排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。

其中较为成熟的MQ产品有IBM WEBSPHERE MQ等等。

MQ是消费-生产者模型的一个典型的代表。

 

RabbitMQ队列  

安装 http://www.rabbitmq.com/install-standalone-mac.html

Linux 直接yum安装rabbitmq省事简便。

启动:rabbitmq-server start 

后台启动:rabbitmq-server -detached

远程链接rabbitmq 需要权限:

我是ssh直接链接Linux的,因此这样授权:

rabbitmqctl add_user root 12345678

rabbitmqctl set_permissions -p / root ".*" ".*" ".*"

 

注意pip3 install pika

 

send端:注意我的Linux机器是用户名:root,密码12345678

#!/usr/bin/env python
import pika

credentials = pika.PlainCredentials('root', '12345678')

parameters = pika.ConnectionParameters(host='192.168.34.139',credentials=credentials)

connection = pika.BlockingConnection(parameters)
channel = connection.channel()

# 声明queue
channel.queue_declare(queue='hello')

# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

 

 

receive端:注意我的Linux机器是用户名:root,密码12345678

# _*_coding:utf-8_*_
__author__ = 'Adamanter'
import pika


credentials = pika.PlainCredentials('root', '12345678')

parameters = pika.ConnectionParameters(host='192.168.34.139',credentials=credentials)

connection = pika.BlockingConnection(parameters)
channel = connection.channel()

# You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
# was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.
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()

  

分别在编辑器中启动send.py,receive.py

send.py 结果: [x] Sent 'Hello World!' 

receive.py 结果:

[*] Waiting for messages. To exit press CTRL+C
[x] Received b'Hello World!'

 

这样就表示成功了。

 

posted @ 2017-08-08 19:17  Adamanter  阅读(129)  评论(0编辑  收藏  举报