วันจันทร์ที่ 23 มีนาคม พ.ศ. 2552

activemq python listener(receive) with stomp.py

ในส่วนที่แล้วมีการพูดถึง send to queue(jms activemq) ไปแล้ว ในส่วนนี้เป็นการรับข้อมูลจาก queue โดยใช้ listener คือ เมื่อมี data เข้ามายัง queue process ก็จะเริ่มทำงาน
ลักษณะการ connect จะคล้ายกับ send แต่จะต่างกันตรงที่ทำการ add class ที่ทำการ listener เข้าไปครับ ตามนี้

file name : listener.py
import time
import sys
import stomp
import logging
from threading import Thread
    
class MyListener(object):
    def on_error(self, headers, message):
        print 'received an error %s' % message
    def on_message(self, headers, message):
        print 'data of headers : %s' % str(headers)
        conn.ack(headers)
        print 'received a message %s' % message
    
class ReceiveConnection():
    def create_connect(self):
        self.conn = stomp.Connection()
    def create_listener(self):
        self.conn.add_listener(MyListener())
        self.conn.start()
        self.conn.connect()
    def __init__(self):
        self.create_connect()
        self.create_listener()
    
conn = ReceiveConnection().conn
    
class Receiver(Thread):
    def __init__(self):
        print 'receive init...'
        Thread.__init__(self)
    def run(self):
        print 'receive run...'
        try:
            conn.subscribe(destination='/queue/qname', ack='client')
            while 1:
                input = raw_input('\nplease q(Enter) to exit:\n')
                if 'q' == input:
                    break
            conn.disconnect()
        except:
            raise Exception('connection to /queue/qname fail!')
    
if "__main__" == __name__:
    print 'start test...'
    r = Receiver()
    r.setName('t_aisws')
    r.start()
    r.join()
    print 'finish test...'

ในกรณีนี้ จะเป็นแบบ ack client คือ เคลีย data จาก queue หลังจาก message listener มีการทำงาน

อีกกรณีเป็นแบบ ack auto คือ เคลีย data จาก q เมื่อรับข้อความจาก queue มาทันที
ทำการแก้ code จากข้างบน โดย บล๊อก
    #conn.ack(headers)
และ เปลี่ยนจาก
    conn.subscribe(destination='/queue/qname', ack='client')
เป็น
    conn.subscribe(destination='/queue/qname', ack='auto')
สองจุดเพียงเท่านี้ ครับ
จบ ๆ ๆ

ไม่มีความคิดเห็น: