Пример #1
0
class PikaFactory(protocol.ReconnectingClientFactory):

    def __init__(self, host='localhost', port=5672, userid='guest', password='guest'):
        self.parameters = pika.ConnectionParameters(
            host=host, port=port,
            credentials=pika.PlainCredentials(userid, password)
        )
        self.client = None
        self.queued_messages = []
        self.read_list = []

    def startedConnecting(self, connector):
        LOG.info('Started to connect to AMQP')

    def buildProtocol(self, addr):
        self.resetDelay()
        LOG.info('Connected AMQP')
        self.client = PikaProtocol(self.parameters)
        self.client.factory = self
        self.client.ready.addCallback(self.client.connected)
        return self.client

    def clientConnectionLost(self, connector, reason):
        LOG.info('Lost connection.  Reason: %s', reason)
        protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason.getErrorMessage())

    def clientConnectionFailed(self, connector, reason):
        LOG.info('Connection failed. Reason: %s', reason)
        protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason.getErrorMessage())

    def send_message(self, exchange=None, routing_key=None, message=None):
        self.queued_messages.append((exchange, routing_key, message))
        if self.client is not None:
            self.client.send()

    def read_messages(self, exchange, routing_key, callback):
        """Configure an exchange to be read from."""
        self.read_list.append((exchange, routing_key, callback))
        if self.client is not None:
            self.client.read(exchange, routing_key, callback)

    def connect(self):

        try:
            reactor.connectTCP(
                host=self.parameters.host,
                port=self.parameters.port,
                factory=self)
        except Exception as e:
            LOG.error(e)
Пример #2
0
 def buildProtocol(self, addr):
     self.resetDelay()
     LOG.info('Connected AMQP')
     self.client = PikaProtocol(self.parameters)
     self.client.factory = self
     self.client.ready.addCallback(self.client.connected)
     return self.client