首页 > 其他 > 详细

RabbitMQ异步收发()

时间:2020-03-29 20:32:39      阅读:78      评论:0      收藏:0      [点我收藏+]

pika提供了支持异步发送模式的selectconnection方法支持异步发送接收(通过回调的方式)。

connectioon建立时回调建立channel, channel建立时一次回调各种declare方法,declare建立时依次回调publish。

同使用blockconnection方法相比,通过wireshark抓包来看,使用 异步的方式会对发包进行一些优化,会将几个包合并成一个大包,然后做一次ack应答从而提高效率,与之相反使用blockconnection时将会做至少两次ack,head一次content一次等。

因此再试用异步的方式时会获得一定的优化。

  1.异步发送publish:

import pika
import time as timer
from time import time

connection = None


def on_open(conn):
    conn.channel(on_open_callback=on_channel_open)


def on_channel_open(channel):
    message = message body value
    for i in range(5):
        channel.basic_publish(‘‘,
                              hello-01,
                              message,
                              pika.BasicProperties(content_type=text/plain,
                                                   delivery_mode=1))

    connection.close()


credentials = pika.PlainCredentials("wjq", "1234")
parameters = pika.ConnectionParameters(host=192.168.139.128, credentials=credentials)

connection = pika.SelectConnection(
    parameters=parameters, on_open_callback=on_open)
try:
    connection.ioloop.start()
    connection.ioloop.poller.open = False
    connection.close()
except KeyboardInterrupt:
    connection.close()
    connection.ioloop.start()

  2.异步接收consum:

import pika
import logging
import traceback
import time as timer
from time import time

mylog = logging.getLogger(pika)
mylog.setLevel(logging.ERROR)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
mylog.addHandler(ch)


def on_open(connection):
    connection.channel(on_open_callback=on_channel_open)


channelg = None
begin_time = time()

# 回调处理函数
def on_message(unused_channel, basic_deliver, properties, body): print("body>>>", body.decode("utf-8")) timer.sleep(0.1) unused_channel.basic_ack(delivery_tag=basic_deliver.delivery_tag) def on_channel_open(channel): try: channel.basic_consume(hello-01, on_message, False) # channel.start_consuming() except (Exception,): print(traceback.format_exc(), ">>>") credentials = pika.PlainCredentials("wjq", "1234") parameters = pika.ConnectionParameters(host=192.168.139.128, credentials=credentials) connection = pika.SelectConnection( parameters=parameters, on_open_callback=on_open) try: connection.ioloop.start() except KeyboardInterrupt: connection.close() connection.ioloop.start()

 

参考地址:

  https://www.cnblogs.com/cwp-bg/p/8426188.html

  https://blog.51cto.com/8415580/1351328

 

RabbitMQ异步收发()

原文:https://www.cnblogs.com/WiseAdministrator/p/12594456.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!