在RabbitMQ中有4種匹配方式宝与,分別是direct(完全匹配)梗醇,fanout(廣播匹配)鳄抒,topic(主題匹配)闯捎,header(標(biāo)題匹配)。
最近做一個(gè)項(xiàng)目有需求想實(shí)現(xiàn)行情實(shí)時(shí)刷新功能要集成這個(gè)RabbitMQ许溅,但是網(wǎng)上一查發(fā)現(xiàn)少的很關(guān)于Topic主題訂閱的就可以說沒有了瓤鼻,研究了一下,下面說一下我的心得:
首先導(dǎo)入框架pod 'RMQClient', '~> 0.10.0'
引用#import <RMQClient.h>
- (void)viewDidLoad {
? ? [super viewDidLoad];
? ? // Do any additional setup after loading the view.
? ? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activeNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
? ? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
#pragma mark - 系統(tǒng)的通知監(jiān)聽
- (void)activeNotification:(NSNotification *)notification{
??? if (_conn == nil) {
??????? [self receiveRabbitServicerMessage];
??? }
}
- (void)backgroundNotification:(NSNotification *)notification{
??? if (_conn) {
??????? [self.conn close];
??????? self.conn = nil;
??? }
}
- (void)dealloc {
???
??? if (_conn) {
??????? [self.conn close];
??????? self.conn = nil;
??? }
??? [[NSNotificationCenter? defaultCenter] removeObserver:self];
???
}
- (void)viewWillAppear:(BOOL)animated{
??? [super viewWillAppear:animated];
??? [self receiveRabbitServicerMessage];
}
- (void)viewWillDisappear:(BOOL)animated{
??? [super viewWillDisappear:animated];
???
??? if (_conn) {
??????? [self.conn close];
??????? self.conn = nil;
??? }
}
- (void)receiveRabbitServicerMessage {
???
??? NSString *url5 = @"amqp://user01:123456@192.168.0.153:5672";
??? /*
amqp:如果你是HTTPS協(xié)議那就是amqps贤重,HTTP就是amqp
user01:用戶名茬祷;
123456:用戶密碼;
192.168.0.153:域名并蝗;
5672:端口碼祭犯;
*/
??? if (_conn == nil) {//[RMQConnectionDelegateLogger new]
??????? _conn = [[RMQConnection alloc] initWithUri:url5 delegate:[RMQConnectionDelegateLogger new]];//代理這樣不用寫代理方法有錯(cuò)誤就會(huì)直接打印日志
??? }
??? [_conn start]; //開始連接
???
??? id<RMQChannel> ch = [_conn createChannel];//創(chuàng)建通道
??? RMQExchange *exchange= [ch topic:@"merchant_exchange" options:RMQExchangeDeclareDurable];//創(chuàng)建交換機(jī) (注意我用的topic所以是topic:option:秸妥,其他模式不一樣)
??? RMQQueue *queue = [ch queue:@"merchant_queue_" options:RMQQueueDeclareExclusive]; //隊(duì)列名稱
??? [queue bind:exchange routingKey:@"merchant_key_1"]; //需要綁定routingKey? (和后臺(tái)約定好,交換機(jī)名稱也是)
??? NSLog(@"Waiting for logs.");
??? [queue subscribe:RMQBasicConsumeNoOptions handler:^(RMQMessage * _Nonnull message) {
??????? NSLog(@"Received==== %@", [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding]);
??? }];
???
}
這就是topic的所有代碼了 沃粗,這時(shí)候后臺(tái)發(fā)送消息處理就可以及時(shí)處理了粥惧。
參考文章:
RabbitMQ——第二篇:IOS版本RabbitMQ集成 - 簡書
有什么好的建議可以和我說哦!QQ:869292512. 或者加我們的技術(shù)交流群543911881陪每,里面大牛云集影晓,可以解決你的技術(shù)難題镰吵。