RabbitMQ基礎_HelloWorld

RabbitMQ基礎 Hello World!

部分內容參考:
金角大王等待唐僧的日子RabbitMQT部分內容
RabbitMQ官網文檔
Ubuntu環境下 RabbitMQ安裝 簡單使用
windows環境下 RabbitMQ 安裝

當前使用版本:python3.7

python不同版本,語法、參數名稱、參數位置可能有變化,注意根據不同版本api調試即可。

基礎

RabbitMQ是一個消息代理。它的核心原理非常簡單:接收和發送消息。RabbitMQ將發送消息和接收消息進行解耦,由此來實現應用程序的異步處理。如果將RabbitMQ視爲一個服務,從大方向來看,RabbitMQ做了三件事情:

  • 收取請求
  • 存儲請求消息
  • 分發請求

引用官網原文,你可以把它想像成一個郵局:你把信件放入郵箱,郵遞員就會把信件投遞到你的收件人處。在這個比喻中,RabbitMQ就扮演着郵箱、郵局以及郵遞員的角色。

名詞解釋

生產(Prouducing)意思就是發送,發送消息的應用程序就是一個(Prouducer),一般用“P”表示。
隊列(Queue),生產者將消息發送給RabbitMQ,是指發送給RabbitMQ的一個隊列。多個生產者可以同時給一個隊列發送消息,同時多個消費者也可以同時從隊列取消息。
**消費者(Consuming)**就是接收消息。一個消費者(Consumer)就是一個等待接收消息的應用程序

初次使用

如果用遠端服務器上的rabbitmq,需要創建對應的用戶和授權。
遠程連接rabbitmq server的話,需要配置權限 噢

首先在rabbitmq server上創建一個用戶
sudo rabbitmqctl  add_user xiaoxia xiaoxia  
同時還要配置權限,允許從外面訪問
sudo rabbitmqctl set_permissions -p / xiaoxia ".*" ".*" ".*"

連接客戶端的時候需要認證參數
credentials = pika.PlainCredentials('xiaoxia', 'xiaoxia')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '10.211.55.5',5672,'/',credentials))
channel = connection.channel()

send.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -*- Author:砍柴少年
# -*- qq:335441537
import pika
credentials = pika.PlainCredentials('xiaoxia', 'xiaoxia')
# 獲取連接
connection = pika.BlockingConnection(pika.ConnectionParameters(   
    '47.244.28.93', 5672, '/', credentials))
# 聲明queue
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.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -*- Author:砍柴少年
# -*- qq:335441537
import pika
credentials = pika.PlainCredentials('xiaoxia', 'xiaoxia')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '47.244.28.93', 5672, '/', credentials))
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 %s" % body)
channel.basic_consume(queue='hello',
                      on_message_callback=callback,
                      auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

分析:👆例子,運行N個receiver端,你會發現send一次後,N個receiver端只有一個會接收。每次send發送一次消息後,N個receiver會輪流有一個去接收消息數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章