上一章將了廣播模式接收多條消息,這一章講主題模式眶俩,也就是topic模式接收消息莹汤。
還是想象一種場(chǎng)景,我發(fā)送一條消息颠印,要讓多個(gè)特定的人收到纲岭。比如,老板今天說线罕,周末研發(fā)中心的所有人加班止潮。那么這樣的話,其他的部門周末照常休息钞楼,只有研發(fā)中心的人才加班喇闸。
(哇,我為什么要舉這個(gè)例子询件,很難受燃乍。。宛琅。)
一刻蟹、接收方法
- (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]);
}];
}
二、發(fā)送方法
- (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];
}
說明:
- 當(dāng)如下指定*為通配符的時(shí)候嘿辟,只有類似fruit.apple,fruit.banana,animals.dog,animals.cat這樣的路由鍵上的消息才會(huì)被轉(zhuǎn)發(fā)
[self receiveWithRoutingKeys:@[@"fruit.*",@"animals.*"]];
- 當(dāng)指定#為通配符的時(shí)候舆瘪,所有的消息都會(huì)被收到片效,比如:test.hello,fruit.apple,animals.dog路由鍵上的消息都會(huì)被轉(zhuǎn)發(fā)
[self receiveWithRoutingKeys:@[@"#"]];
- 當(dāng)使用如下通配符的時(shí)候,只有類似hello.dog,animals.dog,test.dog這樣的路由鍵的消息才會(huì)被轉(zhuǎn)發(fā)
[self receiveWithRoutingKeys:@[@"*.dog",@"*.apple"]];
這一章講完英古,附上DEMO