top of page
Writer's pictureThe Tech Platform

Publisher/Subscriber messaging with Redis

The first thing we need to do is to create a new service that will inherit from “BackgroundService”.


In this class, we must implement an “abstract” method, which will receive and process the messages.

public class Subscriber : BackgroundService
{
    private readonly IConnectionMultiplexer _connectionMultiplexer;

    public Subscriber(IConnectionMultiplexer connectionMultiplexer)
    {
        _connectionMultiplexer = connectionMultiplexer;
    }

    /// <inheritdoc />
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var subscriber = _connectionMultiplexer.GetSubscriber();
        await subscriber.SubscribeAsync("myChannel", (channel, value) =>
        {
            Console.WriteLine($"Received: {value}");
        });
    }
}

As you noticed, we are injecting “IConnectionMultiplexer” again, with this instance we can subscribe to a channel and perform some action with the message received.


In this particular scenario, we are listening “myChannel” and just printing the message content.


The last thing we need to do is register the service, to do it, we need to go to the “Startup” class and add the following in the “ConfigureServices” method:

services.AddHostedService<Subscriber>();

In this case, “Subscriber” is the background service that we created previously.


And, how I can use it?

First of all, we need to have the Redis container running, and then we can run our application.


Once we have our app running, we open our favorite Redis manager, in my case I’m using “Another Redis Desktop Manager” and go to the console.


In the console we need to introduce the following command:

PUBLISH "myChannel" "This is my message"

The command just posts a message to the given channel, in this scenario, we are posting “This is my message” in the “myChannel” channel.


As you can see, we received a “1”, this is command returns the number of clients that received the message.


And this is the output.w


As always you can check the source code from here.




Source: Medium -


The Tech Platform

0 comments

Comments


bottom of page