上一章將了廣播模式接收多條消息,這一章講主題模式,也就是topic模式接收消息。
還是想象一種場景,我發送一條消息,要讓多個特定的人收到。比如,老板今天說,周末研發中心的所有人加班。那么這樣的話,其他的部門周末照常休息,只有研發中心的人才加班。
(哇,我為什么要舉這個例子,很難受。。。)
一、接收方法
- (void)receiveWithRoutingKeys:(NSArray *)keys
{
RMQConnection * connection = [[RMQConnection alloc] initWithDelegate:[RMQConnectionDelegateLogger new]];
[connection start];
id<RMQChannel>channel = [connection createChannel];
RMQExchange * exchange = [channel topic:self.exchangeTF.text options:RMQExchangeDeclareAutoDelete];
RMQQueue * queue = [channel queue:@"" options:RMQQueueDeclareAutoDelete];
for (NSString * routingKey in keys) {
[queue bind:exchange routingKey:routingKey];
}
[queue subscribe:^(RMQMessage * _Nonnull message) {
NSLog(@"%@上收到消息:%@",message.routingKey,[[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding]);
}];
}
二、發送方法
- (void)sendWithRoutingKey:(NSString *)routingKey
{
RMQConnection * connection = [[RMQConnection alloc] initWithDelegate:[RMQConnectionDelegateLogger new]];
[connection start];
id<RMQChannel>channel = [connection createChannel];
RMQExchange * exchange = [channel topic:self.exchangeTF.text options:RMQExchangeDeclareAutoDelete];
[exchange publish:[self.contentTF.text dataUsingEncoding:NSUTF8StringEncoding] routingKey:routingKey];
[connection close];
}
說明:
- 當如下指定*為通配符的時候,只有類似fruit.apple,fruit.banana,animals.dog,animals.cat這樣的路由鍵上的消息才會被轉發
[self receiveWithRoutingKeys:@[@"fruit.*",@"animals.*"]];
- 當指定#為通配符的時候,所有的消息都會被收到,比如:test.hello,fruit.apple,animals.dog路由鍵上的消息都會被轉發
[self receiveWithRoutingKeys:@[@"#"]];
- 當使用如下通配符的時候,只有類似hello.dog,animals.dog,test.dog這樣的路由鍵的消息才會被轉發
[self receiveWithRoutingKeys:@[@"*.dog",@"*.apple"]];
這一章講完,附上DEMO