iOS RMQClient(RabbitMQ)第三章---主题模式接收消息

上一章将了广播模式接收多条消息,这一章讲主题模式,也就是topic模式接收消息。
还是想象一种场景,我发送一条消息,要让多个特定的人收到。比如,老板今天说,周末研发中心的所有人加班。那么这样的话,其他的部门周末照常休息,只有研发中心的人才加班。
(哇,我为什么要举这个例子,很难受。。。)

一、接收方法

- (void)receiveWithRoutingKeys:(NSArray *)keys
{
    RMQConnection * connection = [[RMQConnection alloc] initWithDelegate:[RMQConnectionDelegateLogger new]];
    [connection start];
    idchannel = [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];
    idchannel = [connection createChannel];
    RMQExchange * exchange = [channel topic:self.exchangeTF.text options:RMQExchangeDeclareAutoDelete];
    [exchange publish:[self.contentTF.text dataUsingEncoding:NSUTF8StringEncoding] routingKey:routingKey];
    [connection close];
}

说明:

  1. 当如下指定*为通配符的时候,只有类似fruit.apple,fruit.banana,animals.dog,animals.cat这样的路由键上的消息才会被转发
    [self receiveWithRoutingKeys:@[@"fruit.*",@"animals.*"]];
  2. 当指定#为通配符的时候,所有的消息都会被收到,比如:test.hello,fruit.apple,animals.dog路由键上的消息都会被转发
    [self receiveWithRoutingKeys:@[@"#"]];
  3. 当使用如下通配符的时候,只有类似hello.dog,animals.dog,test.dog这样的路由键的消息才会被转发
    [self receiveWithRoutingKeys:@[@"*.dog",@"*.apple"]];
    这一章讲完,附上DEMO

你可能感兴趣的:(iOS RMQClient(RabbitMQ)第三章---主题模式接收消息)