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.

Revisions

  1. NickCraver created this gist Feb 3, 2022.
    49 changes: 49 additions & 0 deletions RedisExampleListBlocking.linq
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    <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);
    }
    }
    }
    }