1. 程式人生 > >RabbitMQ在Ubuntu 16.04下的安裝與配置及python RabbitMQ佇列使用

RabbitMQ在Ubuntu 16.04下的安裝與配置及python RabbitMQ佇列使用

一、RabbitMQ在Ubuntu 16.04下的安裝與配置

新增源

echo 'deb http://www.rabbitmq.com/debian/ testing main' | sudo tee /etc/apt/sources.list.d/rabbitmq.list

新增公鑰

wget -O- https://www.rabbitmq.com/rabbitmq-release-signing-key.asc | sudo apt-key add -

更新源

sudo apt-get update

安裝rabbitmq-server

sudo apt-get install rabbitmq-server

通過上篇介紹的命令invoke-rc.d rabbitmq-server stop/start/etc我們看見程序是啟動的

[email protected]:/etc/apt/sources.list.d$ invoke-rc.d rabbitmq-server status 
● rabbitmq-server.service - RabbitMQ broker
   Loaded: loaded (/lib/systemd/system/rabbitmq-server.service; enabled; vendor preset: enabled)
   Active: active (running) since 四 2017-05-25 20:42:25 CST; 5min ago
 Main PID: 4865 (beam.smp)
   Status: "Initialized"
   CGroup: /system.slice/rabbitmq-server.service
           ├─4865 /usr/lib/erlang/erts-7.3/bin/beam.smp -W w -A 64 -P 1048576 -t 5000000 -stbt db -zdbbl 32000 -K true -- -root /usr/lib/erlang
           ├─4942 /usr/lib/erlang/erts-7.3/bin/epmd -daemon
           ├─5074 inet_gethost 4
           └─5075 inet_gethost 4

5月 25 20:42:21 xq-VPCEG17YC rabbitmq-server[4865]:               RabbitMQ 3.6.10. Copyright (C) 2007-2017 Pivotal Software, Inc.
5月 25 20:42:21 xq-VPCEG17YC rabbitmq-server[4865]:   ##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
5月 25 20:42:21 xq-VPCEG17YC rabbitmq-server[4865]:   ##  ##
5月 25 20:42:21 xq-VPCEG17YC rabbitmq-server[4865]:   ##########  Logs: /var/log/rabbitmq/
[email protected]
5月 25 20:42:21 xq-VPCEG17YC rabbitmq-server[4865]: ###### ## /var/log/rabbitmq/[email protected] 5月 25 20:42:21 xq-VPCEG17YC rabbitmq-server[4865]: ########## 5月 25 20:42:21 xq-VPCEG17YC rabbitmq-server[4865]: Starting broker... 5月 25 20:42:25 xq-VPCEG17YC rabbitmq-server[4865]: systemd unit for activation check: "rabbitmq-server.service" 5月 25 20:42:25 xq-VPCEG17YC systemd[1]: Started RabbitMQ broker. 5月 25 20:42:25 xq-VPCEG17YC rabbitmq-server[4865]: completed with 0 plugins.

開啟管理頁面 

sudo rabbitmq-plugins enable rabbitmq_management

檢視安裝的外掛 

sudo rabbitmqctl list_users

檢視使用者 

sudo rabbitmqctl list_users

新增管理員使用者 

sudo rabbitmqctl add_user admin admin 
sudo rabbitmqctl set_user_tags admin administrator

用剛設定的賬戶登入管理頁面 


二、python RabbitMQ佇列使用

1. 關於python的queue介紹

    關於python的佇列,內建的有兩種,一種是執行緒queue,另一種是程序queue,但是這兩種queue都是隻能在同一個程序下的執行緒間或者父程序與子程序之間進行佇列通訊,並不能進行程式與程式之間的資訊交換,這時候我們就需要一箇中間件,來實現程式之間的通訊。

2. RabbitMQ

    MQ並不是python內建的模組,而是一個需要你額外安裝的程式,安裝完畢後可通過python中內建的pika模組來呼叫MQ傳送或接收佇列請求。接下來我們就看幾種python呼叫MQ的模式(作者自定義中文形象的模式名稱)與方法。

3. RabbitMQ設定遠端連結賬號密碼

1) 啟動rabbitmq web服務

2) 遠端訪問rabbitmq: 自己增加一個使用者,步驟如下:

(1)  建立一個admin使用者

sudo rabbitmqctl add_user admin 123123

(2)  設定該使用者為administrator角色

sudo rabbitmqctl set_user_tags admin administrator

(3)  設定許可權

sudo rabbitmqctl  set_permissions  -p  '/'  admin '.' '.' '.'

(4)  重啟rabbitmq服務

sudo service rabbitmq-server restart

之後就能用admin使用者遠端連線rabbitmq server了。

4. 輪詢消費模式

此模式下,傳送佇列的一方把訊息存入mq的指定佇列後,若有消費者端聯入相應佇列,即會獲取到訊息,並且佇列中的訊息會被消費掉。

若有多個消費端同時連線著佇列,則會已輪詢的方式將佇列中的訊息消費掉。

接下來是程式碼例項:

producer生產者

# !/usr/bin/env python
import pika
credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.56.19',5672,'/',credentials))
channel = connection.channel()

# 宣告queue
channel.queue_declare(queue='balance')

# 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='balance',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

傳送過佇列後,可在MQ伺服器中檢視佇列狀態

[[email protected] ~]# rabbitmqctl list_queues
Listing queues ...
hello    1

consumer消費者

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

credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.56.19',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='balance')


def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)


channel.basic_consume(callback,
                      queue='balance',
                      no_ack=True)

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

接收佇列後,檢視一下佇列狀態

[[email protected] ~]#  rabbitmqctl list_queues
Listing queues ...
hello    0

5. 佇列持久化

當rabbitMQ意外宕機時,可能會有持久化儲存佇列的需求(佇列中的訊息不消失)。
producer
# Cheng
# !/usr/bin/env python
import pika

credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.56.19',5672,'/',credentials))
channel = connection.channel()

# 宣告queue
channel.queue_declare(queue='durable',durable=True)

# 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='durable',
                      body='Hello cheng!',
                      properties=pika.BasicProperties(
                          delivery_mode=2,  # make message persistent
                      )
                      )
print(" [x] Sent 'Hello cheng!'")
connection.close()

執行後檢視佇列,記下佇列名字與佇列中所含訊息的數量

[[email protected] ~]# rabbitmqctl list_queues
Listing queues ...
durable    1
#重啟rabbitmq
[[email protected] ~]# systemctl restart rabbitmq-server
#重啟完畢後再次檢視
[[email protected] ~]# rabbitmqctl list_queues
Listing queues ...
durable   #佇列以及訊息並未消失
執行消費者程式碼

cunsumer

# Cheng
# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika

credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.56.19',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='durable',durable=True)


def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_consume(callback,
                      queue='durable',
                      #no_ack=True
                      )

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
可正確接收到資訊。

再次檢視佇列的情況。

[[email protected] ~]# rabbitmqctl list_queues
Listing queues ...
durable    0

7. 廣播模式

當producer傳送訊息到佇列後,所有的consumer都會收到訊息,需要注意的是,此模式下producer與concerned之間的關係類似與廣播電臺與收音機,如果廣播後收音機沒有接受到,那麼訊息就會丟失。
建議先執行concerned
concerned
# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika

credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.56.19',5672,'/',credentials))
channel = connection.channel()

channel.exchange_declare(exchange='Clogs',
                         type='fanout')

result = channel.queue_declare(exclusive=True)  # 不指定queue名字,rabbit會隨機分配一個名字,exclusive=True會在使用此queue的消費者斷開後,自動將queue刪除
queue_name = result.method.queue

channel.queue_bind(exchange='Clogs',
                   queue=queue_name)

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


def callback(ch, method, properties, body):
    print(" [x] %r" % body)


channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()

producer

import pika
import sys

credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
    '192.168.56.19',5672,'/',credentials))
channel = connection.channel()

channel.exchange_declare(exchange='Clogs',
                         type='fanout')

message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='Clogs',
                      routing_key='',
                      body=message)
print(" [x] Sent %r" % message)
connection.close()

相關推薦

RabbitMQ在Ubuntu 16.04安裝配置python RabbitMQ佇列使用

一、RabbitMQ在Ubuntu 16.04下的安裝與配置新增源echo 'deb http://www.rabbitmq.com/debian/ testing main' | sudo tee /etc/apt/sources.list.d/rabbitmq.list新

VS2008安裝配置DirectShow SDK 9.0 DirectShow AMCap改裝的問題

靜態庫 cfa -c class 文件目錄 call ref stat and 一、 安裝DirectShow。 我裝的是DirectShow SDK 9.0b。安裝程序名為DXSDK_Jun10.exe。 下載地址:https://pan.

並行作業2:Ubuntu(16.04)安裝配置hadoop(2.7.3)

Ubuntu(16.04)下安裝配置hadoop(2.7.3) 系統採用vm下ubuntu16.04 一、Java環境搭建(參考我的其它部落格) 二、安裝ssh-server並實現免密碼登入 1、下載安裝ssh-server sudo apt-get install op

如何在Linux Ubuntu 16.04安裝開啟PyCharm (轉)

下載 安裝 PyCharm 下載好的檔案的名稱可能是 ‘pycharm-community-2017.2.3.tar.gz’ 首先開啟終端,然後通過下面的命令進入下載檔案所在的資料夾: cd ~/Downloads 或者如果資料夾是中文 cd ~/下載 1

如何在Linux Ubuntu 16.04安裝開啟PyCharm

下載 安裝 PyCharm 下載好的檔案的名稱可能是 ‘pycharm-community-2017.2.3.tar.gz’ 首先開啟終端,然後通過下面的命令進入下載檔案所在的資料夾: cd ~/Downloads 或者如果資料夾是

在Ubuntu 16.04安裝nodejs

.cn ges ubuntu 技術 com apt-get 分享 6.0 images 源安裝: 1.curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash - 2.sudo apt-get insta

windows平臺安裝配置mysql5.7

mysql windows 博主QQ:819594300博客地址:http://zpf666.blog.51cto.com/有什麽疑問的朋友可以聯系博主,博主會幫你們解答,謝謝支持!在windows上安裝mysql5.7需要具有系統的管理員權限。Windows平臺下提供兩種安裝方式:1、mysql二進

Linux安裝配置Nginx

下載 訪問 準備 cep ssi config configure 你會 inpu 一、準備 Nginx版本:nginx-1.7.7.tar.gz 請自行到官網下載對應的版本。 二、步驟 ?在Linux新建一個queenLove用戶 [[email prot

在ubuntu14.04/16.04 安裝Matlab2015b-64bit- Standalone版本

技術 補全 log alt fff mex ora 需要 -c 此安裝過程是對其他作者的隨筆內容進行補全。 1.首先就是掛載鏡像 創建一個掛載的目錄: sudo mkdir /media/matlab 掛載命令: sudo mount -o loop R2015b_gl

Ubuntu 16.04安裝Apache壓力測試工具ab

apt-get gpo 簡單使用 utils sta markdown 測試結果 壓力測試 安裝apache 安裝 sudo apt-get install apache2-utils 簡單使用 # 對http://www.baidu.com/進行100次請求,10個並發請

redis---在CentOS6.5安裝配置

eas 相關 var 可選 tro rip 持久 exec TP 本文詳細介紹redis單機單實例安裝與配置,服務及開機自啟動。如有不對的地方,歡迎大家拍磚o(∩_∩)o (以下配置基於CentOS release 6.5 Final, redis版本3.0.2 [redi

CentOS安裝配置Maven

export http utf uri 阿裏 cor redhat odin ngs 安裝Maven 當前系統 [root@141 ~]# cat /etc/redhat-release CentOS Linux release 7.3.1611 (Core) 下載 h

Ubuntu16.04安裝配置Redis

req get 添加 run 文件 redis安裝 server ubunt bin 一、前提條件 需要連接互聯網,然後執行sudo apt-get update更新軟件包 二、執行安裝命令 sudo apt-get install redis-server 執行後

Centos7KVM的安裝配置創建虛擬機

數據幀 參數 link roo mct 完成 cfg scripts 51cto 我是在VMware Workation上做的實驗進入到系統後,關閉iptables或者firewalld,關閉selinux。並且檢查cpu參數是否支持虛擬化:[root@localhost

linux安裝配置Redis

修改 密碼 ted 路徑 設置密碼 fix 安裝與配置 安裝 bsp 1.安裝 (1)獲取源代碼   wget http://download.redis.io/releases/redis-4.0.8.tar.gz (2)解壓   tar xzvf redis-4.0.8

Ubuntu 16.04 安裝nginx

一、建立一個目錄存放nginx認證祕鑰。命令列進入該目錄 執行 wget http://nginx.org/keys/nginx_signing.key 會在當前目錄中下載該網頁檔案 二、執行sudo apt-key add nginx_signing.key命令將nginx金鑰加

在Ubuntu 16.04安裝 virtualbox 5.0/5.1

不知道為什麼,下載好官方的安裝包之後安裝總是儲存。我放棄了官方的安裝包,想辦法從其他地方安裝。軟體商店試過,一直在安裝,似乎卡住了,最後是通過添加了一個源的方式才裝上的~ 這裡放上安裝的過程 sudo sh -c 'echo "deb http://download.virtua

Ubuntu 16.04安裝Caffe解決 undefined symbol: _ZN5boost6python6detail11init_moduleER11PyModuleDefPFvvE

今天安裝Caffe框架,make時一切正常,但import caffe時出現以下錯誤 >>> import caffe Traceback (most recent call last): File "<stdin>", line 1, in <

ubuntu 16.04安裝 mysql-connector-c-6.1.11-linux-glibc2.12-x86_64.tar.gz

最近在玩MySQL,就想著用c語言去連結資料庫,看了網上的c語言連結資料的例子,怎麼也執行不了; 網上說要安裝一個庫,如下: 安裝:sudo apt-get install libmysqlclient-dev 不知道是不是我電腦的原因,這種裝過以後報了錯誤,好像是:mysql-com

Redis在windows安裝配置

加壓 tro 運行 png 卸載 star 修改 一個 level 一、安裝Redis 1. Redis官網下載地址:http://redis.io/download,下載相應版本的Redis,在運行中輸入cmd,然後把目錄指向解壓的Redis目錄。 2、啟動服務命