使用rabbitmq消息隊列

1、前言

  在python中自己就是存在隊列queue。一個是線程隊列queue,另外一個是進程multiprocessing中的隊列Queue。html

  線程queue:只用於線程之間的數據交互python

  進程Queue:用於同一進程下父進程和子進程之間的數據交互,或者同屬於一個父進程下的多個子進程之間的交互linux

2、RabbitMQ

  若是是多個進程間(不一樣的應用程序之間)、多個系統須要進行數據交互,那麼就能夠使用消息服務來解決這些問題。消息服務擅長於解決多系統、異構系統間的數據交換(消息通知/通信)問題,你也能夠把它用於系統間服務的相互調用(RPC)。RabbitMQ就是當前最主流的消息中間件之一。windows

  RabbitMQ的基礎介紹:點擊查看函數

  實現最簡單的隊列通訊線程

  

  send端  3d

# -*- coding: UTF-8 -*-

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
    'localhost'))

# 聲明一個管道
channel = connection.channel()

# 聲明queue
channel.queue_declare(queue='hello')  # queue的名稱

# 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端  code

# -*- coding: UTF-8 -*-

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
    'localhost'))
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.

# 這個queue名稱就是剛纔send端中聲明的,再次聲明就能保證找到生產者發送的數據
# 若是消費者在生產者以前先啓動了,會找不到這個消息隊列,就會報錯
channel.queue_declare(queue='hello')


def callback(ch, method, properties, body):
    print('--->>', ch, '\n', method, '\n', properties)
    print(" [x] Received %r" % body)

# ch: 聲明的管道channel對象內存地址
#

channel.basic_consume(callback,  # 若是收到消息就調用callback函數來處理消息
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')

# 永遠收下去,沒有就在這卡住
channel.start_consuming()

3、鏈接遠程rabbitmq

  鏈接遠程rabbitmq可能會有認證問題,須要輸入用戶名和密碼server

  windows下設置用戶名、密碼和權限:herehtm

  linux環境下設置用戶名、密碼和權限:here

  基本都在最後面

  send端的設置: 

# -*- conding:utf-8 -*-

import pika

# 認證信息
credentials = pika.PlainCredentials('bigberg', '111111')

connection = pika.BlockingConnection(pika.ConnectionParameters(
    '172.16.200.109', 5672, '/', credentials))

# 聲明一個管道
channel = connection.channel()

# 聲明queue
channel.queue_declare(queue='hello')  # queue的名稱

# 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='from remote server')
print(" [x] Sent 'from remote server'")
connection.close()
相關文章
相關標籤/搜索