RabbitMQ使用Python測試發送接收消息

1、設置rabbitMQ鏡像模式
1.1、創建鏡像模式
rabbitmqctl set_policy ha-all "^" '{"ha-mode":"all"}'
1.2、查看
rabbitmqctl list_policies
rabbitmqctl set_policy [-p <vhost>] [--priority <priority>] [--apply-to <apply-to>] <name> <pattern> <definition>#清除
rabbitmqctl clear_policy [-p <vhost>] <name>#查看
rabbitmqctl list_policies [-p <vhost>]
清除鏡像模式
rabbitmqctl clear_policy -p / ha-all
集羣節點狀態:
{running_nodes,[rabbit@zk_kakfa3,rabbit@zk_kakfa2,rabbit@zk_kakfa1]},

編寫python測試發送、接收消息腳本:
1.3、安裝依賴:
python client
pip install pika

1.4、RabbitMQ控制添加隊列

1.5、python測試發送腳本
more mian.py

import pika
import random,time

credentials = pika.PlainCredentials('testmq', '1qaz2wsx')
#這裏可以連接遠程IP,請記得打開遠程端口
parameters = pika.ConnectionParameters('192.168.12.223',5672,'/',credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()

#channel.queue_declare(queue='hello')
number=1
while True:

          # for i in ['test3']:
    # number = random.randint(1,1000)  
    body = 'hello world {}:'.format(number)
    channel.basic_publish(exchange='{}'.format('test3'),    
                        routing_key='hello',    
                        body=body)    
    print("push message: [x] Sent %s" %body)    
    time.sleep(1)
    number+=1

connection.close()

1.6、python測試接收腳本

#!/usr/bin/env python

-- coding: UTF-8 --

import pika
import random,time
def callback(ch, method, props, body):
#time.sleep(2)
print('recive message:',body)
ch.basic_ack(delivery_tag=method.delivery_tag)
credentials = pika.PlainCredentials('testmq', '1qaz2wsx')
#這裏可以連接遠程IP,請記得打開遠程端口
parameters = pika.ConnectionParameters('192.168.12.223',5672,'/',credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()

channel.basic_consume('test3',callback, auto_ack=False)
#channel.basic_consume('test2',callback, auto_ack=True)
channel.start_consuming()

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