CentOS+Mac+Python+RabbitMQ
阿新 • • 發佈:2018-11-19
1.伺服器安裝
參考連結:http://www.cnblogs.com/pangguoping/p/5720134.html
# cat /etc/redhat-release
CentOS Linux release 7.3.1611 (Core)
yum install epel-release -y
yum install socat -y
yum install erlang -y
rpm -ivh rabbitmq-server-3.6.10-1.el7.noarch.rpm
systemctl start rabbitmq-server
systemctl restart rabbitmq-server
systemctl stop rabbitmq-server
firewall-cmd --add-port=15672/tcp --permanent #開啟15672埠
firewall-cmd --add-port=5672/tcp --permanent #開啟5672埠
2.設定使用者
參考連結:http://www.cnblogs.com/zhen-rh/p/6862350.html
rabbitmqctl add_user admin admin #使用者名稱密碼
rabbitmqctl set_user_tags admin administrator #許可權
rabbitmqctl list_users
rabbitmq-plugins enable rabbitmq_management #網路管理
rabbitmqctl set_permissions -p '/' admin ".*" ".*" ".*" #vhost
http://192.168.154.153:15672 #網頁訪問
3.Mac編譯安裝python 2.7.13(windows/linux略)
3.1安裝python2.7.13 –with-brewed-openssl
參考連結:https://github.com/Homebrew/legacy-homebrew/issues/22816
brew install openssl
brew link openssl --force
brew uninstall python
brew install python -- with-brewed-openssl
brew link --overwrite python
3.2修改pip配置
參考連結:https://www.zhihu.com/question/30941329/answer/151221304
編輯環境變數:
vi ~/.bash_profile
新增新行:
alias pip="/usr/local/bin/python /usr/local/lib/python2.7/site-packages/pip"
立即生效:
source ~/.bash_profile
4.Python測試
參考連結:http://www.cnblogs.com/pangguoping/p/5720134.html
pip install pika
# coding:utf8
import pika
# ############################## 生產者 ##############################
credentials = pika.PlainCredentials('admin', 'admin')
connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.154.153', 5672, '/', credentials))
# 建立頻道
channel = connection.channel()
# 宣告訊息佇列,訊息將在這個佇列中進行傳遞。如果將訊息傳送到不存在的佇列,rabbitmq將會自動清除這些訊息。如果佇列不存在,則建立
channel.queue_declare(queue='hello')
# exchange -- 它使我們能夠確切地指定訊息應該到哪個佇列去。
# 向佇列插入數值 routing_key是佇列名 body是要插入的內容
i=0
while i<20:
i+=1
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World! i={}'.format(i))
print("開始佇列")
# 緩衝區已經flush而且訊息已經確認傳送到了RabbitMQ中,關閉連結
connection.close()
# coding:utf8
import pika
import time
# ########################### 消費者 ###########################
credentials = pika.PlainCredentials('admin', 'admin')
connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.154.153', 5672, '/', credentials))
channel = connection.channel()
# 宣告訊息佇列,訊息將在這個佇列中進行傳遞。如果佇列不存在,則建立
# channel.queue_declare(queue='test')
# 定義一個回撥函式來處理,這邊的回撥函式就是將資訊打印出來。
def callback(ch, method, properties, body):
time.sleep(0.5) ##休眠0.5s
print(" [x] Received %r" % body)
# 告訴rabbitmq使用callback來接收資訊
channel.basic_consume(callback,
queue='hello',
no_ack=True)
# no_ack=True表示在回撥函式中不需要傳送確認標識
print(' [*] Waiting for messages. To exit press CTRL+C')
# 開始接收資訊,並進入阻塞狀態,佇列裡有資訊才會呼叫callback進行處理。按ctrl+c退出。
channel.start_consuming()