Skip to content

Instantly share code, notes, and snippets.

@NickCraver
Created February 3, 2022 19:49
Show Gist options
  • Save NickCraver/6fc7c86d0610b0a02c0b3366fa5bdecf to your computer and use it in GitHub Desktop.
Save NickCraver/6fc7c86d0610b0a02c0b3366fa5bdecf to your computer and use it in GitHub Desktop.
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