Skip to content

Redis channels

Andrey Bulygin edited this page May 21, 2013 · 1 revision

Home

To start working with Redis channels all you should do is to call IRedisClient.SubscribeAsync(params string[] channels) or IRedisClient.PSubscribeAsync(params string[] channels) method. These methods will return IRedisSubscription interface that allows you to subscribe or unsubscribe from the other channels and to receive messages from subscribed channels.

To receive messages you can call IRedisSubscription.ReadMessageAsync() that will return message from channel. Keep in mind that you are working now not with high abstraction, so from channel could be read not only messages that were published by other clients but also other types of messages, so you can arrange work with cannel and manage them the way you need. To read more about what messages could be sent to your channel visit http://redis.io/topics/pubsub page. Also there can be different strategies to receive and process channel massages and because of IRedisSubscription.ReadMessageAsync() returns Task object you can easily organize Event-based Asynchronous Pattern or use async/await feature.

ReadMessageAsync has a useful overload which allows you to filter messages you are interested in.

[Test]
public void Publish_Subscribe_WithFilter()
{
	using (var subscriber = CreateClient().SubscribeAsync("channel").Result)
	{
		using (var publisher = CreateClient())
		{
			publisher.PublishAsync("channel", "Some message").Wait();
			var channelMessage = subscriber.ReadMessageAsync(ChannelMessageType.Message | 
									 ChannelMessageType.PMessage).Result;
			Assert.AreEqual(ChannelMessageType.Message, channelMessage.MessageType);
			Assert.AreEqual("channel", channelMessage.Channels[0]);
			Assert.AreEqual("Some message", channelMessage.Value.As<string>());
		}
	}
}
Clone this wiki locally