温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-26 13:02:06 来源:网络 阅读:286 作者:纪仁旺 栏目:系统运维

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()

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI