This article mainly describes how the. NET Core uses the Redis publishing subscription, the small part feels quite good, now shares to everybody, also gives everybody to make a reference. Let's take a look at it with a little knitting.
Redis is a very powerful memory database that is typically used as a cache, but not just as a cache, such as the well-known distributed framework Dubbo can use Redis as a service registry. Next, let's introduce the Publish/subscribe feature of. NET core using Redis.
Redis Publish Subscriptions
A Redis Publish Subscription (PUB/SUB) is a message communication pattern: the Sender (pub) sends a message and the Subscriber (sub) receives the message.
Redis clients can subscribe to any number of channels.
Shows the relationship between channel Channel1 and the three client--client2, CLIENT5, and client1 subscribing to this channel:
When a new message is sent to channel Channel1 via the PUBLISH command, the message is sent to the three clients subscribed to it:
Using Redis commands
First, two clients are subscribed to the Redismessage channel via the Subscribe redismessage command:
Then open a Redis client and use the command publish Redismessage "message content" to publish the message
Using the. NET Core implementation
Here I choose the connection drive for Stackexchange.redis, here to note is Servicestack.redis connection drivers have become commercially available, with restrictions of 4.0 and later, so choose from a free and easy-to-use Stackexchange.redis, using NuGet to install.
Establishing a subscription client
Create connection using (connectionmultiplexer Redis = Connectionmultiplexer.connect ("127.0.0.1:6379")) { Isubscriber sub = Redis. Getsubscriber (); Subscribe to a channel sub named messages . Subscribe ("Messages", (channel, message) = { //output received message Console.WriteLine ($ "[{DATETIME.NOW:HH:MM:SS}] { Message} "); Console.WriteLine ("Subscribed to Messages"); Console.readkey ();}
Build a publishing client
Create connection using (connectionmultiplexer Redis = Connectionmultiplexer.connect ("127.0.0.1:6379")) { Isubscriber sub = Redis. Getsubscriber (); Console.WriteLine ("Please enter any characters, enter exit Exit"); string input; Do { input = Console.ReadLine (); Sub. Publish ("Messages", input); } while (Input! = "Exit");}
The following runs a publishing client with two subscription clients: