当前位置: 首页>>代码示例>>Python>>正文


Python BrokerConnection.connect方法代码示例

本文整理汇总了Python中kombu.BrokerConnection.connect方法的典型用法代码示例。如果您正苦于以下问题:Python BrokerConnection.connect方法的具体用法?Python BrokerConnection.connect怎么用?Python BrokerConnection.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在kombu.BrokerConnection的用法示例。


在下文中一共展示了BrokerConnection.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: FanoutPublisher

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class FanoutPublisher(PluginBase):

    def __init__(self):

        if app.debug:
            setup_logging(loglevel='DEBUG', loggers=[''])

        self.connection = BrokerConnection(app.config['AMQP_URL'])
        try:
            self.connection.connect()
        except Exception as e:
            LOG.error('Failed to connect to AMQP transport %s: %s', app.config['AMQP_URL'], e)
            raise RuntimeError

        self.channel = self.connection.channel()
        self.exchange_name = app.config['AMQP_TOPIC']

        self.exchange = Exchange(name=self.exchange_name, type='fanout', channel=self.channel)
        self.producer = Producer(exchange=self.exchange, channel=self.channel)

        LOG.info('Configured fanout publisher on topic "%s"', app.config['AMQP_TOPIC'])

    def pre_receive(self, alert):

        return alert

    def post_receive(self, alert):

        LOG.info('Sending message %s to AMQP topic "%s"', alert.get_id(), app.config['AMQP_TOPIC'])
        LOG.debug('Message: %s', alert.get_body())

        self.producer.publish(alert.get_body(), declare=[self.exchange], retry=True)
开发者ID:bernytt,项目名称:alerta-ui,代码行数:34,代码来源:amqp.py

示例2: RabbitMQHandler

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class RabbitMQHandler(object):
    def __init__(self, connection_string, exchange):
        self._connection = BrokerConnection(connection_string)
        self._connections = set([self._connection])  # set of connection for the heartbeat
        self._exchange = Exchange(exchange, durable=True, delivry_mode=2, type='topic')
        self._connection.connect()
        monitor_heartbeats(self._connections)

    def _get_producer(self):
        producer = producers[self._connection].acquire(block=True, timeout=2)
        self._connections.add(producer.connection)
        return producer

    def publish(self, item, contributor):
        with self._get_producer() as producer:
            producer.publish(item, exchange=self._exchange, routing_key=contributor, declare=[self._exchange])

    def info(self):
        if not self._is_active:
            return {}
        with self._get_producer() as producer:
            res = producer.connection.info()
            if 'password' in res:
                del res['password']
            return res
开发者ID:kinnou02,项目名称:kirin,代码行数:27,代码来源:rabbitmq_handler.py

示例3: run

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
    def run(self):  
        # Setup connection
        mainLogger.debug('Connecting to Redis on %s %s %s' % (
            agentConfig['redis_host'], agentConfig['redis_port'], agentConfig['redis_db'])
        )
        connection = BrokerConnection(
                        hostname=agentConfig['redis_host'],
                        transport="redis",
                        virtual_host=agentConfig['redis_db'],
                        port=int(agentConfig['redis_port'])
        )
        connection.connect()
        consumer = Consumer(connection)

        while True:
            try:
               consumer.consume()
            except Empty:
               mainLogger.debug('No tasks, going to sleep')
               # sleep is patched and triggers context switching
               # for eventlet
               time.sleep(1)
                
        mainLogger.debug('Waiting')
        mainLogger.debug('Done & exit')
开发者ID:coulix,项目名称:pdftojpg_agent,代码行数:27,代码来源:agent.py

示例4: Messaging

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class Messaging(object):

    amqp_opts = {
        'amqp_queue': '',                                   # do not send to queue by default
        'amqp_topic': 'notify',
        'amqp_url': 'amqp://guest:[email protected]:5672//',  # RabbitMQ
        # 'amqp_url': 'mongodb://localhost:27017/kombu',    # MongoDB
        # 'amqp_url': 'redis://localhost:6379/',            # Redis
        # 'amqp_url': 'sqs://ACCESS_KEY:[email protected]'        # AWS SQS (must define amqp_queue)
        # 'amqp_sqs_region': 'eu-west-1'                    # required if SQS is used
    }

    def __init__(self):

        config.register_opts(Messaging.amqp_opts)

        if CONF.debug:
            setup_logging(loglevel='DEBUG', loggers=[''])

        self.connection = None
        self.connect()

    def connect(self):

        if not CONF.amqp_url:
            return

        if CONF.amqp_url.startswith('sqs://'):
            CONF.amqp_url = 'sqs://' + CONF.amqp_url[6:].replace('/', '%2F')

        if CONF.amqp_sqs_region:
            transport_options = {'region': CONF.amqp_sqs_region}
        else:
            transport_options = {}

        self.connection = BrokerConnection(
            CONF.amqp_url,
            transport_options=transport_options
        )
        try:
            self.connection.connect()
        except Exception as e:
            LOG.error('Failed to connect to AMQP transport %s: %s', CONF.amqp_url, e)
            sys.exit(1)

        LOG.info('Connected to broker %s', CONF.amqp_url)

    def disconnect(self):

        return self.connection.release()

    def is_connected(self):

        return self.connection.connected
开发者ID:alvsgithub,项目名称:alerta,代码行数:56,代码来源:amqp.py

示例5: __init__

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class Audit:
    def __init__(self, hostname='localhost', port='5672',
                 userid='', password='', virtual_host='graylog',
                 exchange=None):
        self.hostname = hostname
        self.port = port
        self.userid = userid
        self.password = password
        self.virtual_host = virtual_host
        self.connection = BrokerConnection(virtual_host=virtual_host)
        self.exchange_setup = exchange or ExchangeSetup()

    def custom_exchange(self, exchange, exchange_type, routing_key, queue):
        """Broker exchange can be set after the object has been instantiated.

        Args:
            exchange (str): Exchange name
            exchange_type (str): AMQP exchange type, see your broker manual
            routing_key (str)
            queue (str)
        """
        self.exchange_setup.exchange = exchange
        self.exchange_setup.exchange_type = exchange_type
        self.exchange_setup.routing_key = routing_key
        self.exchange_setup.queue = queue

    def log(self, message):
        """Pushes argument object to message broker.

        Args:
            message (json/gelp): Message can depend on third-party log software
                Graylog uses gelp format: https://www.graylog.org/resources/gelf/
        """
        if (type(message) is not str) or (message == ''):
            print 'Unable to log empty message'
            return False
        if len(message) > 8192:
            print 'Message size too large'
            return False

        self.connection.connect()
        channel = self.connection.channel()
        exchange = Exchange(self.exchange_setup.exchange,
                            type=self.exchange_setup.exchange_type)

        bound_exchange = exchange(channel)
        bound_exchange.declare()

        # example_message = '{"short_message":"Kombu", "host":"example.org"}'
        message = bound_exchange.Message(message)
        bound_exchange.publish(message, routing_key=self.exchange_setup.routing_key)

        self.connection.release()
开发者ID:magicpotion,项目名称:audit,代码行数:55,代码来源:audit.py

示例6: Publisher

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class Publisher(object):
    def __init__(self, connection_string, exchange, is_active=True):
        self._is_active = is_active
        self.is_connected = True
        if not is_active:
            self.is_connected = False
            return

        self._connection = BrokerConnection(connection_string)
        self._connections = set([self._connection])#set of connection for the heartbeat
        self._exchange = Exchange(exchange, durable=True, delivry_mode=2, type='topic')
        self._connection.connect()
        monitor_heartbeats(self._connections)

    def _get_producer(self):
        producer = producers[self._connection].acquire(block=True, timeout=2)
        self._connections.add(producer.connection)
        return producer

    def publish(self, item, contributor):
        if not self._is_active:
            return

        with self._get_producer() as producer:
            try:
                producer.publish(item, exchange=self._exchange, routing_key=contributor, declare=[self._exchange])
                self.is_connected = True
            except socket.error:
                self.is_connected = False
                logging.getLogger(__name__).debug('Impossible to publish message !')
                raise

    def info(self):
        result = {
            "is_active": self._is_active,
            "is_connected": self.is_connected
        }
        if not self._is_active:
            return result

        with self._get_producer() as producer:
            res = producer.connection.info()
            if 'password' in res:
                del res['password']
            for key, value in res.items():
                result[key] = value
        return result
开发者ID:nberard,项目名称:Chaos,代码行数:49,代码来源:publisher.py

示例7: MqServer

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class MqServer( object ):
    """
    exchange='E_X7_W2S', queue='Q_X7_W2S',routing_key = 'RK_X7_W2S'
    """
    
    def __init__(self, callback, kwargs ):
        self.callback = callback
        if( kwargs ):
            self.kwargs = kwargs
        else:
            self.kwargs = MqDict
            
    def create_queue(self, hostname="localhost", userid="guest", password="guest", virtual_host="/"): 
        self.conn = BrokerConnection(hostname, userid,password, virtual_host )   
        #define Web2Server exchange
        exchange = Exchange(self.kwargs["X7_E"], type="direct")
        self.queue = Queue(self.kwargs["X7_Q"], exchange, routing_key=self.kwargs["X7_RK"])    
        channel = self.conn.channel()
        consumer = Consumer(channel, self.queue, callbacks=[self.callback])
        consumer.consume()
        self.conn.connect()

        
        
    def connect(self, hostname="localhost", userid="guest", password="guest", virtual_host="/"): 
        self.conn = BrokerConnection(hostname, userid,password, virtual_host )   
        #define Web2Server exchange
        exchange = Exchange(self.kwargs["X7_E"], type="direct")
        self.queue = Queue(self.kwargs["X7_Q"], exchange, routing_key=self.kwargs["X7_RK"])    
        channel = self.conn.channel()

        consumer = Consumer(channel, self.queue, callbacks=[self.callback])
        consumer.consume()
    
    def run(self, once=False):
        if( once ):
            self.conn.drain_events()
        else:
            while True:
                self.conn.drain_events()
    
    def get(self):
        message = self.queue.get(block=True)
        message.ack()
        return message
开发者ID:k3coby,项目名称:xeven,代码行数:47,代码来源:x7_mq.py

示例8: FanoutPublisher

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class FanoutPublisher(PluginBase):

    def __init__(self, name=None):
        if app.config['DEBUG']:
            setup_logging(loglevel='DEBUG', loggers=[''])

        self.connection = BrokerConnection(AMQP_URL)
        try:
            self.connection.connect()
        except Exception as e:
            LOG.error('Failed to connect to AMQP transport %s: %s', AMQP_URL, e)
            raise RuntimeError

        self.channel = self.connection.channel()
        self.exchange_name = AMQP_TOPIC

        self.exchange = Exchange(name=self.exchange_name, type='fanout', channel=self.channel)
        self.producer = Producer(exchange=self.exchange, channel=self.channel)

        super(FanoutPublisher, self).__init__(name)

        LOG.info('Configured fanout publisher on topic "%s"', AMQP_TOPIC)

    def pre_receive(self, alert):
        return alert

    def post_receive(self, alert):
        LOG.info('Sending message %s to AMQP topic "%s"', alert.get_id(), AMQP_TOPIC)

        try:
            body = alert.serialize  # alerta >= 5.0

            # update body's datetime-related fields  with utc-aware values
            body.update({key: body[key].replace(tzinfo=pytz.utc) for key in ['createTime', 'lastReceiveTime', 'receiveTime']})
        except Exception:
            body = alert.get_body()  # alerta < 5.0

        LOG.debug('Message: %s', body)
        self.producer.publish(body, declare=[self.exchange], retry=True)

    def status_change(self, alert, status, text):
        return
开发者ID:freeseacher,项目名称:alerta-contrib,代码行数:44,代码来源:alerta_amqp.py

示例9: Messaging

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class Messaging(object):

    amqp_opts = {
        'amqp_queue': 'alerts',
        'amqp_topic': 'notify',
        'amqp_url': 'amqp://guest:[email protected]:5672//',  # RabbitMQ
        # 'amqp_url': 'mongodb://localhost:27017/kombu',    # MongoDB
        # 'amqp_url': 'redis://localhost:6379/',            # Redis
    }

    def __init__(self):

        config.register_opts(Messaging.amqp_opts)

        self.connection = None
        self.channel = None
        self.connect()

    def connect(self):

        if not CONF.amqp_url:
            return

        self.connection = BrokerConnection(CONF.amqp_url)
        try:
            self.connection.connect()
        except Exception as e:
            LOG.error('Failed to connect to AMQP transport %s: %s', CONF.amqp_url, e)
            sys.exit(1)
        self.channel = self.connection.channel()

        LOG.info('Connected to broker %s', CONF.amqp_url)

    def disconnect(self):

        return self.connection.release()

    def is_connected(self):

        return self.connection.connected
开发者ID:fendris,项目名称:alerta,代码行数:42,代码来源:amqp.py

示例10: main

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
def main():
    cfg = {'hostname':'localhost', 'userid':'guest', 'password':'guest', 'virtual_host':'/', 'port':5672}
    transport = 'pika'
    #transport = 'librabbitmq'
    connection = BrokerConnection(transport=transport, **cfg)
    connection.connect()

    cfg = {'name':'simple-test-1', 'auto_delete':True, 'durable':False, 'delivery_mode':'transient'}
    channel = connection.channel()
    exchange = Exchange(channel=channel, **cfg)
    #exchange = exchange_def(channel)

    routing_key = 'simple-test-1-route'
    queue = Queue(exchange=exchange, routing_key=routing_key, **cfg)

    channel = connection.channel()
    producer = Producer(channel=channel, exchange=exchange, routing_key=routing_key)

    channel = connection.channel()
    consumer = Consumer(channel=channel, queues=[queue], callbacks=[receive])
    consumer.consume()

    def serve_forever():
        while True:
            #print 'drain'
            #gevent.sleep(0.0001)
            connection.drain_events(timeout=1)
    def publish_forever():
        while True:
            producer.publish(loremIpsum)
            gevent.sleep(0.0001)

    #g1, g2 = gevent.spawn(publish_forever), gevent.spawn(serve_forever)
    g2 = gevent.spawn(serve_forever)
    g1 = gevent.spawn(publish_forever)
    gevent.joinall([g1, g2])
开发者ID:blazetopher,项目名称:pyon,代码行数:38,代码来源:messaging.py

示例11: test_pika

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class test_pika(unittest.TestCase):

    def purge(self, names):
        chan = self.connection.channel()
        map(chan.queue_purge, names)

    def setUp(self):
        self.connection = BrokerConnection(transport="pika")
        try:
            self.connection.connect()
        except socket.error:
            self.connected = False
        else:
            self.connected = True
        self.exchange = Exchange("tamqplib", "direct")
        self.queue = Queue("tamqplib", self.exchange, "tamqplib")

    def test_produce__consume(self):
        if not self.connected:
            raise SkipTest("Broker not running.")
        chan1 = self.connection.channel()
        producer = Producer(chan1, self.exchange)

        producer.publish({"foo": "bar"}, routing_key="tamqplib")
        chan1.close()

        chan2 = self.connection.channel()
        consumer = Consumer(chan2, self.queue)
        message = consumeN(self.connection, consumer)
        self.assertDictEqual(message[0], {"foo": "bar"})
        chan2.close()
        self.purge(["tamqplib"])

    def test_produce__consume_multiple(self):
        if not self.connected:
            raise SkipTest("Broker not running.")
        chan1 = self.connection.channel()
        producer = Producer(chan1, self.exchange)
        b1 = Queue("pyamqplib.b1", self.exchange, "b1")
        b2 = Queue("pyamqplib.b2", self.exchange, "b2")
        b3 = Queue("pyamqplib.b3", self.exchange, "b3")

        producer.publish("b1", routing_key="b1")
        producer.publish("b2", routing_key="b2")
        producer.publish("b3", routing_key="b3")
        chan1.close()

        chan2 = self.connection.channel()
        consumer = Consumer(chan2, [b1, b2, b3])
        messages = consumeN(self.connection, consumer, 3)
        self.assertItemsEqual(messages, ["b1", "b2", "b3"])
        chan2.close()
        self.purge(["pyamqplib.b1", "pyamqplib.b2", "pyamqplib.b3"])

    def test_timeout(self):
        if not self.connected:
            raise SkipTest("Broker not running.")
        chan = self.connection.channel()
        self.purge([self.queue.name])
        consumer = Consumer(chan, self.queue)
        self.assertRaises(socket.timeout, self.connection.drain_events,
                timeout=0.3)
        consumer.cancel()

    def test_basic_get(self):
        chan1 = self.connection.channel()
        producer = Producer(chan1, self.exchange)
        producer.publish({"basic.get": "this"}, routing_key="basic_get")
        chan1.close()

        chan2 = self.connection.channel()
        queue = Queue("amqplib_basic_get", self.exchange, "basic_get")
        queue = queue(chan2)
        queue.declare()
        for i in range(50):
            m = queue.get()
            if m:
                break
            time.sleep(0.1)
        self.assertEqual(m.payload, {"basic.get": "this"})
        chan2.close()

    def tearDown(self):
        if self.connected:
            self.connection.close()
开发者ID:mixedpuppy,项目名称:kombu,代码行数:87,代码来源:disabled_pika.py

示例12: event2amqp

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class event2amqp():

    def __init__(self,host,port,user,password,virtual_host, exchange_name,identifier,maxqueuelength,queue_dump_frequency):

        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.virtual_host = virtual_host
        self.exchange_name = exchange_name
        self.identifier = identifier
        self.maxqueuelength = maxqueuelength
        self.queue_dump_frequency = queue_dump_frequency

        self.connection_string = None

        self.connection = None
        self.channel = None
        self.producer = None
        self.exchange = None
        self.queue = deque([])

        self.tickage = 0

        self.load_queue()


    def create_connection(self):
        self.connection_string = "amqp://%s:%[email protected]%s:%s/%s" % (self.user,self.password,self.host,self.port,self.virtual_host)
        try:        
            self.connection = BrokerConnection(self.connection_string)
            return True
        except:
            func = sys._getframe(1).f_code.co_name
            error = str(sys.exc_info()[0])
            logger.error("[Canopsis] Unexpected error: %s in %s" % (error,func))
            return False

    def connect(self):
        logger.info("[Canopsis] connection with : %s" % self.connection_string)
        try:
            self.connection.connect()
            if not self.connected():
                return False
            else:
                self.get_channel()
                self.get_exchange()
                self.create_producer()                
                return True
        except:
            func = sys._getframe(1).f_code.co_name
            error = str(sys.exc_info()[0])
            logger.error("[Canopsis] Unexpected error: %s in %s" % (error,func))
            return False

    def disconnect(self):
        try:        
            if self.connected():
                self.connection.release()
            return True
        except:
            func = sys._getframe(1).f_code.co_name
            error = str(sys.exc_info()[0])
            logger.error("[Canopsis] Unexpected error: %s in %s" % (error,func))
            return False

    def connected(self):
        try:
            if self.connection.connected:            
                return True
            else:
                return False
        except:
            return False

    def get_channel(self):
        try:
            self.channel = self.connection.channel()
        except:
            func = sys._getframe(1).f_code.co_name
            error = str(sys.exc_info()[0])
            logger.error("[Canopsis] Unexpected error: %s in %s" % (error,func))
            return False

    def get_exchange(self):
        try:
            self.exchange =  Exchange(self.exchange_name , "topic", durable=True, auto_delete=False)
        except:
            func = sys._getframe(1).f_code.co_name
            error = str(sys.exc_info()[0])
            logger.error("[Canopsis] Unexpected error: %s in %s" % (error,func))
            return False

    def create_producer(self):
        try:
            self.producer = Producer(
                            channel=self.channel,
                            exchange=self.exchange,
                            routing_key=self.virtual_host
                            )
#.........这里部分代码省略.........
开发者ID:Morkxy,项目名称:shinken,代码行数:103,代码来源:canopsis_broker.py

示例13: BrokerConnection

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
from socket import gethostname
from time import time

from kombu import BrokerConnection

files = ['bulletin.pdf', 'med_4p_120k.pdf', 'small_45k.pdf', 'math_11p.pdf']
#files = ['bulletin.pdf',]

connection = BrokerConnection(
                hostname='rh2.dev.novagile.fr',
                transport="redis",
                virtual_host=0,
                port=6379)

print "Connection Producer to Redis"
connection.connect()

queue = connection.SimpleQueue("pdf_to_jpg")

for f in files:
    # open as binary
    my_file = open(f, "rb")
    my_file.seek(0)
    my_file_bcontent = my_file.read()
    my_file.close()

    # Push !
    queue.put({"file_content": my_file_bcontent,
                "file_name": f,
                "hostname":  gethostname(),
                "timestamp": time()},
开发者ID:coulix,项目名称:pdftojpg_agent,代码行数:33,代码来源:producer.py

示例14: RabbitMQHandler

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class RabbitMQHandler(object):
    def __init__(self, connection_string, exchange):
        self._connection = BrokerConnection(connection_string)
        self._connections = set([self._connection])  # set of connection for the heartbeat
        self._exchange = Exchange(exchange, durable=True, delivry_mode=2, type='topic')
        self._connection.connect()
        monitor_heartbeats(self._connections)

    def _get_producer(self):
        producer = producers[self._connection].acquire(block=True, timeout=2)
        self._connections.add(producer.connection)
        return producer

    def publish(self, item, contributor):
        with self._get_producer() as producer:
            producer.publish(item, exchange=self._exchange, routing_key=contributor, declare=[self._exchange])

    def info(self):
        if not self._is_active:
            return {}
        with self._get_producer() as producer:
            res = producer.connection.info()
            if 'password' in res:
                del res['password']
            return res

    def listen_load_realtime(self):
        log = logging.getLogger(__name__)

        def callback(body, message):
            task = task_pb2.Task()
            try:
                # `body` is of unicode type, but we need str type for
                # `ParseFromString()` to work.  It seems to work.
                # Maybe kombu estimate that, without any information,
                # the body should be something as json, and thus a
                # unicode string.  On the c++ side, I didn't manage to
                # find a way to give a content-type or something like
                # that.
                body = str(body)
                task.ParseFromString(body)
            except DecodeError as e:
                log.warn('invalid protobuf: {}'.format(str(e)))
                return

            log.info('getting a request: {}'.format(task))
            if task.action != task_pb2.LOAD_REALTIME or not task.load_realtime:
                return

            feed = convert_to_gtfsrt(RealTimeUpdate.all(task.load_realtime.contributors))

            with self._get_producer() as producer:
                producer.publish(feed.SerializeToString(), routing_key=task.load_realtime.queue_name)

        route = 'task.load_realtime.*'
        log.info('listening route {} on exchange {}...'.format(route, self._exchange))
        rt_queue = Queue('', routing_key=route, exchange=self._exchange, durable=False, auto_delete=True)
        with connections[self._connection].acquire(block=True) as conn:
            self._connections.add(conn)
            with Consumer(conn, queues=[rt_queue], callbacks=[callback]):
                while True:
                    try:
                        conn.drain_events(timeout=1)
                    except socket.timeout:
                        pass
开发者ID:pbougue,项目名称:kirin,代码行数:67,代码来源:rabbitmq_handler.py

示例15: Server

# 需要导入模块: from kombu import BrokerConnection [as 别名]
# 或者: from kombu.BrokerConnection import connect [as 别名]
class Server(object):
	"""
	This Server class is used to provide an RPC server

	:keyword server_id: Id of the server
	:keyword amqp_host: The host of where the AMQP Broker is running.
	:keyword amqp_user: The username for the AMQP Broker.
	:keyword amqp_password: The password for the AMQP Broker.
	:keyword amqp_vhost: The virtual host of the AMQP Broker.
	:keyword amqp_port: The port of the AMQP Broker.
	:keyword ssl: Use SSL connection for the AMQP Broker.
	:keyword threaded: Use of multithreading. If set to true RPC call-execution
		will processed parallel (one thread per call) which dramatically improves
		performance.


	"""
	
	def __init__(self, 
				server_id,
				amqp_host='localhost', 
				amqp_user ='guest',
				amqp_password='guest',
				amqp_vhost='/',
				amqp_port=5672,
				ssl=False,
				threaded=False):
		self.logger = logging.getLogger('callme.server')
		self.logger.debug('Server ID: %s' % server_id)
		self.server_id = server_id
		self.threaded = threaded
		self.do_run = True
		self.is_stopped = True
		self.func_dict={}
		self.result_queue = queue.Queue()
		target_exchange = Exchange("server_"+server_id+"_ex", "direct", durable=False,
								auto_delete=True)	
		self.target_queue = Queue("server_"+server_id+"_queue", exchange=target_exchange, 
							auto_delete=True, durable=False)
		
		
		
		self.connection = BrokerConnection(hostname=amqp_host,
                              userid=amqp_user,
                              password=amqp_password,
                              virtual_host=amqp_vhost,
                              port=amqp_port,
                              ssl=ssl)
		try:
			self.connection.connect()
		except IOError:
			self.logger.critical("Connection Error: Probably AMQP User has not enough permissions")
			raise ConnectionError("Connection Error: Probably AMQP User has not enough permissions")
		
		self.channel = self.connection.channel()
		
		self.publish_connection = BrokerConnection(hostname=amqp_host,
                              userid=amqp_user,
                              password=amqp_password,
                              virtual_host=amqp_vhost,
                              port=amqp_port,
                              ssl=ssl)
		self.publish_channel = self.publish_connection.channel()
		
		# consume
		self.consumer = Consumer(self.channel, self.target_queue)
		if self.threaded == True:
			self.consumer.register_callback(self._on_request_threaded)
		else:
			self.consumer.register_callback(self._on_request)
		self.consumer.consume()
		
		self.logger.debug('Init done')
		
	def _on_request(self, body, message):
		"""
		This method is automatically called when a request is incoming. It 
		processes the incomming rpc calls in a serial manner (no multithreading)

		:param body: the body of the amqp message already unpickled by kombu
		:param message: the plain amqp kombu.message with aditional information
		"""
		self.logger.debug('Got Request')
		rpc_req = body
		
		if not isinstance(rpc_req, RpcRequest):
			self.logger.debug('Not an RpcRequest Instance')
			return
		
		self.logger.debug('Call func on Server %s' %self.server_id)
		try:
			self.logger.debug('corr_id: %s' % message.properties['correlation_id'])
			self.logger.debug('Call func with args %s' % repr(rpc_req.func_args))
			
			result = self.func_dict[rpc_req.func_name](*rpc_req.func_args)
			
			self.logger.debug('Result: %s' % repr(result))
			self.logger.debug('Build respnse')
			rpc_resp = RpcResponse(result)
		except Exception as e:
#.........这里部分代码省略.........
开发者ID:mkisto,项目名称:callme,代码行数:103,代码来源:server.py


注:本文中的kombu.BrokerConnection.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。