rabbitmq util

This commit is contained in:
Yax 2018-07-13 19:03:46 +02:00
parent c86b5b6e87
commit e95f59bb87
2 changed files with 113 additions and 42 deletions

View file

@ -7,56 +7,44 @@ from threading import Thread
import logging
import json
from core import processor
from util import rabbit
logger = logging.getLogger(__name__)
class MailConsumer(rabbit.Consumer):
def process_message(chan, method, properties, body):
def process(self, channel, method, properties, body):
try:
topic = method.routing_key
data = json.loads(body)
try:
topic = method.routing_key
data = json.loads(body)
if topic == 'mail.message':
if "STACOSYS" in data['subject']:
logger.info('new message => {}'.format(data))
processor.enqueue({'request': 'new_mail', 'data': data})
if topic == 'mail.message':
if "STACOSYS" in data['subject']:
logger.info('new message => {}'.format(data))
processor.enqueue({'request': 'new_mail', 'data': data})
else:
logger.info('ignore message => {}'.format(data))
else:
logger.info('ignore message => {}'.format(data))
else:
logger.warn('unsupported message [topic={}]'.format(topic))
except:
logger.exception('cannot process message')
class MessageConsumer(Thread):
def run(self):
credentials = pika.PlainCredentials(
config.rabbitmq['username'], config.rabbitmq['password'])
connection = pika.BlockingConnection(pika.ConnectionParameters(host=config.rabbitmq['host'], port=config.rabbitmq[
'port'], credentials=credentials, virtual_host=config.rabbitmq['vhost']))
channel = connection.channel()
channel.exchange_declare(exchange=config.rabbitmq['exchange'],
exchange_type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange=config.rabbitmq['exchange'],
queue=queue_name,
routing_key='mail.message')
channel.basic_consume(process_message,
queue=queue_name,
no_ack=True)
channel.start_consuming()
def stop(self):
self.loop = False
logger.warn('unsupported message [topic={}]'.format(topic))
except:
logger.exception('cannot process message')
def start():
logger.info('start rmqclient')
c = MessageConsumer()
#c = MessageConsumer()
#c.start()
credentials = pika.PlainCredentials(config.rabbitmq['username'], config.rabbitmq['password'])
parameters = pika.ConnectionParameters(
host=config.rabbitmq['host'],
port=config.rabbitmq['port'],
credentials=credentials,
virtual_host=config.rabbitmq['vhost']
)
connection = rabbit.Connection(parameters)
c = MailConsumer(connection, config.rabbitmq['exchange'], 'mail.message')
c.start()
#print('exit rmqclient ' + str(c))