在RabbitMQ中有4种匹配方式,分别是direct(完全匹配),fanout(广播匹配),topic(主题匹配),header(标题匹配)。
最近做一个项目有需求想实现行情实时刷新功能要集成这个RabbitMQ,但是网上一查发现少的很关于Topic主题订阅的就可以说没有了,研究了一下,下面说一下我的心得:
首先导入框架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 - 系统的通知监听
- (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协议那就是amqps,HTTP就是amqp
user01:用户名;
123456:用户密码;
192.168.0.153:域名;
5672:端口码;
*/
if (_conn == nil) {//[RMQConnectionDelegateLogger new]
_conn = [[RMQConnection alloc] initWithUri:url5 delegate:[RMQConnectionDelegateLogger new]];//代理这样不用写代理方法有错误就会直接打印日志
}
[_conn start]; //开始连接
id<RMQChannel> ch = [_conn createChannel];//创建通道
RMQExchange *exchange= [ch topic:@"merchant_exchange" options:RMQExchangeDeclareDurable];//创建交换机 (注意我用的topic所以是topic:option:,其他模式不一样)
RMQQueue *queue = [ch queue:@"merchant_queue_" options:RMQQueueDeclareExclusive]; //队列名称
[queue bind:exchange routingKey:@"merchant_key_1"]; //需要绑定routingKey (和后台约定好,交换机名称也是)
NSLog(@"Waiting for logs.");
[queue subscribe:RMQBasicConsumeNoOptions handler:^(RMQMessage * _Nonnull message) {
NSLog(@"Received==== %@", [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding]);
}];
}
这就是topic的所有代码了 ,这时候后台发送消息处理就可以及时处理了。
参考文章:
RabbitMQ——第二篇:IOS版本RabbitMQ集成 - 简书
有什么好的建议可以和我说哦!QQ:869292512. 或者加我们的技术交流群543911881,里面大牛云集,可以解决你的技术难题。
网友评论