1. 程式人生 > 實用技巧 >【訊息佇列】之 RabbitMQ安裝

【訊息佇列】之 RabbitMQ安裝

RabbitMQ

環境

centos 7

安裝

vi /etc/yum.repos.d/rabbitmq-erlang.repo

[rabbitmq-erlang]
name=rabbitmq-erlang
baseurl=https://dl.bintray.com/rabbitmq-erlang/rpm/erlang/21/el/7
gpgcheck=1
gpgkey=https://dl.bintray.com/rabbitmq/Keys/rabbitmq-release-signing-key.asc
repo_gpgcheck=0
enabled=1

yum install erlang socat -y
rpm -Uvh https://dl.bintray.com/rabbitmq/all/rabbitmq-server/3.7.18/rabbitmq-server-3.7.18-1.el7.noarch.rpm
systemctl start rabbitmq-server
systemctl enable rabbitmq-server
systemctl status rabbitmq-server

安裝ui外掛

rabbitmq-plugins enable rabbitmq_management
chown -R rabbitmq:rabbitmq /var/lib/rabbitmq/

建立賬號授權

rabbitmqctl add_user admin rabbitmq
rabbitmqctl set_user_tags admin administrator
rabbitmqctl set_permissions -p / admin ".*" ".*" ".*"

systemctl restart rabbitmq-server

關閉防火牆

iptables -F

登陸

http://ip:15672 輸入賬號密碼 admin/rabbitmq

python測試

生產者

#!/usr/bin/env python   
# -*- coding: UTF-8 -*- 
import pika
#連上rabbitMQ
connection=pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel=connection.channel()

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

#n RabbitMQ a message can never be sent directly to the queue,it always needs to go through an exchange.
#向佇列裡發資料
import json
data = json.dumps({"a":1})


channel.basic_publish(exchange='',
                      routing_key='hello1',
                      body=data)
print("[x]Sent'HelloWorld!'")
connection.close()

消費者

import poka
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', port=5672))
channel = connection.channel()
channel.queue_declare(queue='hello1')
#回撥函式
def callback(ch, method, properties, body):
	def callback(ch, method, properties, body):

channel.basic_consume(queue="hello1",auto_ack=True,on_message_callback=callback)
#監聽
channel.start_consuming()