欢迎光临
我们一直在努力

RabbitMQ使用Python测试发送接收消息

1、设置rabbitMQ镜像模式

1.1、普通模式
集群各个节点仅有相同的元数据,即队列的结构
消息实体只存在于其中一个节点rabbit01(或者rabbit02)
当消息进入rabbit01节点的Queue后,consumer从rabbit02节点消费时,RabbitMQ会临时在rabbit01、rabbit02间进行消息传输,把A中的消息实体取出并经过B发送给consumer

1.2、镜像模式
把需要的队列做成镜像队列,存在与多个节点,消息实体会主动在镜像节点间同步,属于RabbitMQ的HA方案。
副作用也很明显,除了降低系统性能外,如果镜像队列数量过多,加之大量的消息进入,集群内部的网络带宽将会被这种同步通讯大大消耗掉。

1.1、创建镜像模式
启动rabbit
rabbitmq-server start -detached
rabbitmqctl set_policy ha-all "^" ‘{"ha-mode":"all"}’
rabbitmqctl set_policy ha-all "^" ‘{"ha-mode":"all","ha-sync-mode":"automatic"}’
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()

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。