Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redis Blocking BRPOP example
<Query Kind="Program">
<NuGetReference>StackExchange.Redis</NuGetReference>
<Namespace>StackExchange.Redis</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
</Query>
private static RedisKey WorkToDoList = "work-to-do-list";
private static RedisChannel WorkToDoChannel = "work-to-do";
// List-backed, blocker example
async Task Main()
{
var connection = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
var db = connection.GetDatabase();
_ = Task.Run(BlockingWait);
while (true)
{
var message = "Hey " + DateTime.UtcNow.ToString("u");
Console.WriteLine("Publishing " + message);
await db.ListLeftPushAsync(WorkToDoList, message);
await Task.Delay(1000);
}
}
// Consumer side
public async Task BlockingWait()
{
var connection = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
var db = connection.GetDatabase();
Console.WriteLine("Starting blocking wait");
while (true)
{
var result = await db.ExecuteAsync("BRPOP", WorkToDoList, 1000);
if (!result.IsNull)
{
var arr = (RedisValue[])result;
if (arr.Length == 2)
{
// 0: list name (for listening to multiple)
// 1: value popped
var message = (string)arr[1];
Console.WriteLine("Message received: " + message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment