How to publish and subscribe with redis by. Net core

Time:2021-4-23

Redis is a memory database with very strong performance. It is generally used as a cache, but it can not only be used as a cache. For example, the famous distributed framework Dubbo can use redis as a service registry. Next, let’s introduce how. Net core uses redis’s publish / subscribe function.

Redis publish subscribe

Redis publish subscribe (Pub / sub) is a kind of message communication mode: the sender (PUB) sends the message and the subscriber (sub) receives the message.
Redis clients can subscribe to any number of channels.

The following figure shows the relationship between channel 1 and the three clients that subscribe to this channel — client2, client5 and client1

When a new message is sent to channel 1 through the publish command, the message will be sent to the three clients that subscribe to it

Use redis command

First, make two clients subscribe to the redismessage channel through the subscribe redismessage command

Then open a redis client and use the command publish redismessage “message content” to publish the message

Implementation with. Net core

The connection driver I choose here is StackExchange.Redis What should be noted here is that ServiceStack.Redis Connection driver has been commercialized gradually, 4.0 and above versions have restrictions, so choose free and easy to use StackExchange.Redis , use nuget to install.

Establish subscription client

//Create a connection
using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
{
  ISubscriber sub = redis.GetSubscriber();

  //Subscribe to the channel named messages

  sub.Subscribe("messages", (channel, message) => {

    //Output received message
    Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
  });
  Console.WriteLine ("subscribed messages");
  Console.ReadKey();
}

Establish publishing client

//Create a connection
using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
{
  ISubscriber sub = redis.GetSubscriber();

  Console.WriteLine (please enter any character and exit to exit);

  string input;

  do
  {
    input = Console.ReadLine();
    sub.Publish("messages", input);
  } while (input != "exit");
}

One publishing client and two subscription clients are running as follows:

Demo download

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.