订阅交换作为单独的功能

时间:2017-05-15 20:09:12

标签: ios swift rabbitmq

我对RabbitMQ使用单例模式:

final class ServiceBus{

    static let Instance = ServiceBus()

    var conn: RMQConnection;
    var ch: RMQChannel;
    var clientExchange: RMQExchange;
    var clientQueue: RMQQueue;  

    private init() {
        let delegate = RMQConnectionDelegateLogger()
        self.conn = RMQConnection(uri: myUri, delegate: delegate)
        self.conn.start()
        self.ch = self.conn.createChannel()
        self.clientExchange = ch.direct("Client")
        self.clientQueue = ch.queue("", options: .exclusive)
    }
}

我也有很多页面,我需要通过我的sessionID订阅交换。我现在在每个ViewController上再次订阅:

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()        
        ServiceBus.Instance.clientQueue.bind(ServiceBus.Instance.clientExchange, routingKey: sessionID)
        ServiceBus.Instance.clientQueue.subscribe({(_ message: RMQMessage) -> Void in
            let message = String(data: message.body, encoding: .utf8)!        
            //...
        })
    }
}

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()        
        ServiceBus.Instance.clientQueue.bind(ServiceBus.Instance.clientExchange, routingKey: sessionID)
        ServiceBus.Instance.clientQueue.subscribe({(_ message: RMQMessage) -> Void in
            let message = String(data: message.body, encoding: .utf8)!        
            //...
        })
    }
}

如何创建单独的函数来订阅交换并在不同的ViewControllers中使用相同的单独函数?

0 个答案:

没有答案