python监听activemq一段时间后自动断开的问题成功解决

问题描述

在我的博客《工具使用篇——python操作ActiveMq》中,我详细的介绍了python是怎样注册登记监听activemq,并且向消息队列中推送数据的,但是最近就出现了一个新得得情况:
python程序通过stomp协议监听actvemq,在一段时间之后,当我再往消息队列里推送消息时,监听程序却没有反应,打开控制台,返现,监听程序已经掉线~~,这就很尴尬了。

我的监听程序

import sys
import os
import stomp
user = "admin"
password = "admin"
host = "127.0.0.1"
port = 61613
dest="test"

destination = sys.argv[1:2] or ["/topic/event"]
print(sys.argv)
destination = destination[0]
class MyListener(object):
    def __init__(self, conn):
        self.conn = conn
        self.count = 0
        self.start = time.time()
    def on_error(self, headers, message):
        print('received an error %s' % message)
    def on_message(self, headers, message):
        print(message)
        if message == "SHUTDOWN":
            conn.disconnect()
            sys.exit(0)
        else:
            print(message)

conn = stomp.Connection(host_and_ports=[("localhost", 61613)])
conn.set_listener('', MyListener(conn))
# conn.start()
conn.connect(login=user, passcode=password)
conn.subscribe(destination=dest, ack='auto', id="")
print("Waiting for messages...")
while 1:
    time.sleep(10)

解决办法

问题出来以后,到处搜寻解决得办法,但是很遗憾,网上对于python操作activemq得文章本来就不多,并且,基本搜遍了全网也搜不到对应的解决办法,最后还是直接看源码,并求助开发文档:
在这里插入图片描述
发现在传参的时候keepalive可能需要注意以下,然后就在connect的时候设置keepalive为True,很遗憾没用。
随后看官方说明文档stompy.pdf,发现有这样一个内部参数:
在这里插入图片描述
照着改写了内部类,发现也没啥用,该断开开始断开,并且这个函数都没有被激发。

解决办法

在原来的基础上一段时间,强制的断开监听并重新注册监听

import sys
import os
import stomp
user = "admin"
password = "admin"
host = "127.0.0.1"
port = 61613
dest="test"

destination = sys.argv[1:2] or ["/topic/event"]
print(sys.argv)
destination = destination[0]
class MyListener(object):
    def __init__(self, conn):
        self.conn = conn
        self.count = 0
        self.start = time.time()
    def on_error(self, headers, message):
        print('received an error %s' % message)
    def on_message(self, headers, message):
        print(message)
        if message == "SHUTDOWN":
            conn.disconnect()
            sys.exit(0)
        else:
            print(message)

conn = stomp.Connection(host_and_ports=[("localhost", 61613)])
conn.set_listener('', MyListener(conn))
def  connect_subscribe():
	conn.connect(login=user, passcode=password)
	conn.subscribe(destination=dest, ack='auto', id="")
connect_subscribe()
def re_connect_subscribe():
    """
    重新登记注册
    :return:
    """
    conn.disconnect()
    time.sleep(3)
    connect_subscribe()
print("Waiting for messages...")
i=0
while 1:
    i+=1
    time.sleep(10)
    # print(i)
    if i==6*3:
        #3分钟之后重新注册一次,防止时间过长,连接断开
        re_connect_subscribe()
        i=0

如此,便达到了我们的效果。
虽然解决了该问题,但是我觉得这种方法可能比较笨,找到好的方法在补充。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值