Tornado与Rabbitmq消息服务的集成方法

#-*- coding:utf-8 -*-
#!/usr/bin/python


import json
import redis
import logging


try:
    import pika
    from pika.adapters.tornado_connection import TornadoConnection
except ImportError:
    pika = None


try:
    import tornado
    import tornado.ioloop
except ImportError:
    tornado = None


logger = logging.getLogger('main.recieve_tornado')


class PikaClient(object):
    callbacks = {}


    def __init__(self):
        if tornado is None:
            raise Exception('You must add tornado to your requirements!')
        if pika is None:
            raise Exception('You must add pika to your requirements!')


        self.ioloop = tornado.ioloop.IOLoop.instance()
        self.connection = None
        self.channel = None


        self._delivery_tag = 0
        self.parameters = pika.URLParameters("amqp://admin:admin@192.167.1.101:5672/todo")


    def connect(self):
        self.connection = TornadoConnection(self.parameters, on_open_callback=self.on_connected, stop_ioloop_on_close=False)
        self.connection.add_on_close_callback(self.on_closed)


    def on_connected(self, connection):
        logger.info('PikaClient: connected to RabbitMQ')
        self.connection.channel(self.on_exchange_declare)


    def on_exchange_declare(self, channel):
        logger.info('PikaClient: Channel %s open, Declaring exchange' % channel)
        self.channel = channel
        self.channel.exchange_declare(self.on_queue_declare, exchange='compute', type='fanout')


    def on_queue_declare(self, method_frame):
        logger.info('PikaClient: Channel open, Declaring queue')
        self.channel.queue_declare(self.on_queue_bind, queue='compute_queue', durable=True)


    def on_queue_bind(self, method_frame):
        logger.info('Queue bound')
        self.channel.queue_bind(self.on_consume_bind, queue="compute_queue", exchange="compute", routing_key="compute_queue")


    def on_consume_bind(self, frame):
        self.channel.basic_qos(prefetch_count=1)
        self.channel.basic_consume(self.on_response, queue='compute_queue', no_ack=False)


    def on_response(self, channel, method, properties, body):
        message=json.loads(body)
        userID = message.get("userId","No User")
        userID = userID.lower()
        self.con.set(userID, body)
        channel.basic_ack(delivery_tag = method.delivery_tag)
        logger.info('Recieve a new Message: '+message)


    def on_closed(self, connection):
        logger.info('PikaClient: rabbit connection closed')
        self.connection.close()
        self.channel.close()
        self.ioloop.stop()


#常用的调用方式:


#-*- coding:utf-8 -*-


import os
import tornado.web
from url import urls
from models.recieve import PikaClient


class Application(tornado.web.Application):
    def __init__(self):
        self.recieve = PikaClient()
        self.recieve.connect()


        handlers = urls
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            cookie_secret="this_is_cookie_code",
            xsrf_cookies=False,
            login_url="/",
            debug=True
            )
        tornado.web.Application.__init__(self, handlers, **settings)



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值