【问题标题】:How to integrate Pika with Qt?如何将 Pika 与 Qt 集成?
【发布时间】:2020-09-02 15:34:58
【问题描述】:

最近,一位用户询问如何将 Pika 与 Qt 一起使用,但意外地,当我即将发布我的答案时,该用户删除了,这让我有机会通过自动答案提出这个问题,并尝试公开各种解决方案:

【问题讨论】:

    标签: python pyqt5 amqp pyside2 pika


    【解决方案1】:

    使用BlockingConnectionstart_consuming() 方法必须在另一个线程中执行,此外必须知道回调是在辅助线程中执行的,因此如果要更新 GUI,则必须发出信号

    import threading
    
    from PyQt5 import QtCore, QtWidgets
    # or
    # from PySide2 import QtCore, QtWidgets
    
    import pika
    
    
    class RabbitMQManager(QtCore.QObject):
        messageChanged = QtCore.pyqtSignal(str)
        # or
        # messageChanged = QtCore.Signal(str)
    
        def __init__(self, *, parameters=None, parent=None):
            super().__init__(parent)
    
            self._connection = pika.BlockingConnection(parameters)
    
        @property
        def connection(self):
            return self._connection
    
        def start(self):
            channel = self.connection.channel()
            channel.queue_declare(queue="hello")
            channel.basic_consume(
                queue="hello", on_message_callback=self._callback, auto_ack=True,
            )
            threading.Thread(target=channel.start_consuming, daemon=True).start()
    
            print(" [*] Waiting for messages. To exit press CTRL+C")
    
        def _callback(self, ch, method, properties, body):
            print(" [x] Received %r" % body)
            self.messageChanged.emit(body.decode())
    
    
    def main():
    
        import signal
        import sys
    
        # https://stackoverflow.com/a/6072360
        signal.signal(signal.SIGINT, signal.SIG_DFL)
    
        app = QtWidgets.QApplication(sys.argv)
    
        w = QtWidgets.QTextEdit()
        w.resize(640, 480)
        w.show()
    
        credentials = pika.PlainCredentials("user", "user")
        parameters = pika.ConnectionParameters("127.0.0.1", 5672, "/", credentials)
    
        rabbit_manager = RabbitMQManager(parameters=parameters)
        rabbit_manager.start()
    
        rabbit_manager.messageChanged.connect(w.append)
    
        sys.exit(app.exec_())
    
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多