Windows 10家庭中文版,Python 3.6.4,stomp.py 4.1.21
ActiveMQ支持Python訪問,提供了基于STOMP協(xié)議(端口為61613)的庫。
ActiveMQ的官文Cross Language Clients中給出了更詳細的介紹,并附有示例代碼,如下圖:
第一行為常規(guī)Python訪問,第二行為使用Jython訪問的方式,四個操作。

Python訪問ActiveMQ需要使用stomp.py,見其官網(wǎng)。
下載官網(wǎng)的代碼,解壓,命令行進入其目錄,使用pyhthon setup.py install即可安裝好,然后就可以使用stomp.py了。
官方示例代碼:給隊列test發(fā)送一個消息,也可以把第7行的destination的“/queue/”去掉,只剩test。
import stompconn = stomp.Connection()conn.set_listener('', MyListener())conn.start()conn.connect('admin', 'password', wait=True)conn.send(body=' '.join(sys.argv[1:]), destination='/queue/test')conn.disconnect()測試結果:test隊列接收到消息數(shù)量增加了

stomp.Connection()默認是connect.StompConnection11(協(xié)議1.1),還可以可以選擇1.0、1.2。

在官方代碼中,stomp.Connection()的參數(shù)為空,實際上可以有很多參數(shù),比如,設置Broker的IP地址和端口,如下:其中的host_and_ports就是設置IP和端口的。

IP和端口設置示例:
c = stomp.Connection([('127.0.0.1', 62613)])
這里我犯錯了,端口我協(xié)程了8161(ActiveMQ的Web訪問的端口),經(jīng)查詢(百度搜索到stackoverflow.com)才知,STOMP協(xié)議用的是61613(ActiveMQ的配置文件中):

ActiveMQ官網(wǎng)的四個測試:
發(fā)送消息到隊列Queue屬于 點對點模式,不可以重復消費;
發(fā)送消息到主題Topic屬于 發(fā)布/訂閱模式,可以重復消費;
# Send a Message to an Apache ActiveMQ Queue import stomp conn = stomp.Connection10() conn.start() conn.connect() conn.send('SampleQueue', 'Simples Assim') conn.disconnect()# Receive a Message from an Apache ActiveMQ Queueimport stompimport time class SampleListener(object): def on_message(self, headers, msg): print(msg) conn = stomp.Connection10() conn.set_listener('SampleListener', SampleListener()) conn.start() conn.connect() conn.subscribe('SampleQueue') time.sleep(1) # secs conn.disconnect()# Send a Message to an Apache ActiveMQ Topic import stomp conn = stomp.Connection10() conn.start() conn.connect() conn.send('/topic/SampleTopic', 'Simples Assim') conn.disconnect()# Receive a Message from an Apache ActiveMQ Topic (1)import stompimport time class SampleListener(object): def on_message(self, headers, msg): print(msg) conn = stomp.Connection10() conn.set_listener('SampleListener', SampleListener()) conn.start() conn.connect() conn.subscribe('/topic/SampleTopic') time.sleep(1) # secs conn.disconnect()# Receive a Message from an Apache ActiveMQ Topic (2)import stompimport time class SampleListener(object): def on_message(self, headers, msg): print(msg) conn = stomp.Connection10() conn.set_listener('SampleListener', SampleListener()) conn.start() conn.connect(headers={'client-id':'SampleClient'}) conn.subscribe(destination='/topic/SampleTopic', headers={'activemq.subscriptionName':'SampleSubscription'}) time.sleep(1) # secs conn.disconnect()
新聞熱點
疑難解答