. Net core how to use Redis to publish and subscribe, coreredis
Redis is a memory database with very powerful 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 the service registration center. Next we will introduce how. net core uses Redis's publish/subscribe function.
Redis publish and subscribe
Redis pub/sub is a message communication mode: the sender (pub) sends messages, and the subscriber (sub) receives messages.
Redis clients can subscribe to any number of channels.
Shows the relationship between channel channel1 and the three clients that subscribe to the channel-client2, client5, and client1:
When a new message is sent to channel channel1 through the PUBLISH command, the message is sent to the three clients that subscribe to it:
Use Redis commands
First, use the subscribe redismessage command to subscribe to the redismessage channel between the two clients:
Then open a Redis client and run the command publish redismessage "message content" to publish the message.
Using. net core
The connection driver I selected here is StackExchange. redis, please note that ServiceStack. the Redis connection driver has been gradually commercialized, and Version 4.0 and later have restrictions. Therefore, the free and easy-to-use StackExchange is selected. use nuget to install Redis.
Create a subscription Client
// Create a connection to using (ConnectionMultiplexer redis = ConnectionMultiplexer. connect ("127.0.0.1: 6379") {ISubscriber sub = redis. getSubscriber (); // subscribe to the sub channel named messages. subscribe ("messages", (channel, message) =>{// output the received message Console. writeLine ($ "[{DateTime. now: HH: mm: ss}] {message} ") ;}); Console. writeLine ("subscribed to messages"); Console. readKey ();}
Create a publishing Client
// Create a connection to using (ConnectionMultiplexer redis = ConnectionMultiplexer. connect ("127.0.0.1: 6379") {ISubscriber sub = redis. getSubscriber (); Console. writeLine ("enter any character and enter exit to exit"); string input; do {input = Console. readLine (); sub. publish ("messages", input);} while (input! = "Exit ");}
A publishing client and two subscription clients are running below:
Download Demo
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.