Redis Pub/Sub with .net Core

Ercan Erdoğan
Innovile
Published in
3 min readMay 22, 2021

As the needs of the users increase in order to meet these needs, we have to figure out some new architectural solutions.

Meeting those increased needs became harder by centralized applications. Therefore we have started to use distributed systems widely.

Redis is one of the good solutions to handle distributed caching mechanisms. On the other hand, “Redis Labs” provides us with miscellaneous solutions. One of them is about messaging.

First of all, I want to explain that what is the message broker and why we need it?

“Modern software applications have moved from being a single monolithic unit to loosely coupled collections of services. While this new architecture brings many benefits, those services still need to interact with each other, creating the need for robust and efficient messaging solutions.”(1)

So, what does it mean Publisher and Subscriber?

In software architecture, publish-subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead categorize published messages into classes without knowledge of which subscribers, if any, there may be. Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are. (2)

source : http://intro2libsys.com/focused-redis-topics/day-two/pubsub

After these theoretical explains question is that how can we start to use Redis.

  • To install Redis by docker
docker run --name myredis -p 6379:6379 -d redis

To test redis in the command line we need to enter Redis container.

docker exec -it myredis

To publish test message to the channel

publish test-channel "welcome to redis"

To able to receive this message we need to subscribe to this channel. Otherwise, this message doesn’t arrive at us. This message could be seen just by members that subscribe to this channel.

subscribe test-channel

All right, how can we use this with .net core?

We need 2 solutions. One of them is the publisher and another is a subscriber.

Create publisher project

dotnet new console --name redis-publisher

Create subscriber project

dotnet new console --name redis-subscriber

To use Redis in .net core project there is a package that name is StackExchange.Redis. We need to add reference this package to both projects.

adding StackExchange.Redis package

Publisher:

Subscriber:

Run Result:

This is a simple solution to understand how Redis pub/sub works. I am planning to write about other message broker systems for example RabbitMQ and Kafka. Finally, we will compare all of them according to advantages and disadvantages.

Thank you for your time, see you at the next post :)

source code : https://github.com/ercanerdogan/RedisPubSub.git

--

--