This article mainly introduces how .net core uses Redis to publish and subscribe. The editor thinks it is quite good. Now I will share it with you and give it a reference. Let’s follow the editor to take a look.
Redis is a very powerful in-memory database. It is generally used as a cache, but it can not only be used as a cache, such as the famous distributed framework dubbo. Redis can be used as a service registration center. Next, we will introduce the publish/subscribe function of .net core using Redis.
Redis publish and subscribe
Redis publish and subscribe (pub/sub) is a message communication model: the sender (pub) sends the message and the subscriber (sub) receives it information.
Redis clients can subscribe to any number of channels.
The following figure shows the relationship between channel channel1 and the three clients that subscribe to this channel - client2, client5 and client1:
When When a new message is sent to channel channel1 through the PUBLISH command, this message will be sent to the three clients that subscribe to it:
Use Redis command
First, use the subscribe redismessage command to subscribe the two clients to the redismessage channel:
Then open a Redis client and use the command publish redismessage " Message content "Publish message
Using .net core to implement
The connection driver I chose here is StackExchange.Redis, which is required here Note that the ServiceStack.Redis connection driver has gradually become commercialized, and versions 4.0 and above have limitations, so choose the free and easy-to-use StackExchange.Redis and install it using nuget.
Establish a subscription client
##
//创建连接 using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379")) { ISubscriber sub = redis.GetSubscriber(); //订阅名为 messages 的通道 sub.Subscribe("messages", (channel, message) => { //输出收到的消息 Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}"); }); Console.WriteLine("已订阅 messages"); Console.ReadKey(); }
//创建连接 using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379")) { ISubscriber sub = redis.GetSubscriber(); Console.WriteLine("请输入任意字符,输入exit退出"); string input; do { input = Console.ReadLine(); sub.Publish("messages", input); } while (input != "exit"); }
The above is the detailed content of Introduction to the publish and subscribe method using Redis in .net core. For more information, please follow other related articles on the PHP Chinese website!