.Net5 uses Redis to implement publish/subscribe

As a representative of high-performance memory database, Redis is generally used as a cache, but it is not only that, Redis can also be used as a service registry. Let's talk about how to use Redis to implement subscription/publishing under .Net5.

Redis pub/sub

Redis publish and subscribe (pub/sub) simply means that the sender (pub) sends a message, and the subscriber (sub) receives the message.
Insert picture description here

In daily life, for example, the WeChat public account we pay attention to will often push various information to us. This is a typical publish and subscribe. How is this done? Let's take a look.

.Net5 implementation

Note: The following projects are created using the .Net5 console program
. 1. First create a RedisPublish project to simulate the publishing server.
Introduce the Redis package
Insert picture description here
2. Write the following code

   static void Main(string[] args)
        {
			try
			{
				//创建一个公众号--创建一个主题
				Console.WriteLine("SendMessage");
				IRedisClientsManager redisClientManager = new PooledRedisClientManager("127.0.0.1:6379");
				string topicname = "Tom is a good cat";
				RedisPubSubServer pubSubServer = new RedisPubSubServer(redisClientManager, topicname)
				{
					OnMessage = (channel, msg) =>
					{
			//此处可以写入日志记录
						Console.WriteLine("___________________________________________________________________");
					},
					OnStart = () =>
					{
						Console.WriteLine("发布服务已启动");
						Console.WriteLine("___________________________________________________________________");
					},
					OnStop = () => { Console.WriteLine("发布服务停止"); },
					OnUnSubscribe = channel => { Console.WriteLine(channel); },
					OnError = e => { Console.WriteLine(e.Message); },
					OnFailover = s => { Console.WriteLine(s); },
				};
				//接收消息
				pubSubServer.Start();
				while (true)
				{
					Console.WriteLine("请输入推送内容");
					string message = Console.ReadLine();
					redisClientManager.GetClient().PublishMessage(topicname, message);
				}
			}
			catch (Exception ex)
			{

				Console.WriteLine(ex.Message);
			}

		}

3. Create a RedisSub project to simulate the subscription client and
write the following code

        static void Main(string[] args)
        {
			try
			{
				using (RedisClient consumer = new RedisClient("127.0.0.1", 6379))
				{

					Console.WriteLine($"这是订阅客户端");
					var subscription = consumer.CreateSubscription();
					//接受到消息时
					subscription.OnMessage = (channel, msg) =>
					{
						if (msg != "CTRL:PULSE")
						{
						//此处可以写入日志记录
	
						}

					};
					//订阅频道时
					subscription.OnSubscribe = (channel) =>
					{
						Console.WriteLine("订阅客户端:开始订阅" + channel);
					};
					//取消订阅频道时
					subscription.OnUnSubscribe = (a) => { Console.WriteLine("订阅客户端:取消订阅"); };
					//订阅频道
					string topicname = "Tom is a good cat";
					subscription.SubscribeToChannels(topicname);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

4. Turn on the publishing server and simulate two subscribing clients. The
Insert picture description here
publishing server inputs the push content, and the two subscribing clients receive the push content. The
effect is as follows:
![Insert picture description here](https://img-blog.csdnimg.cn/20210330205318418.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNz3G4hubmV0L

In this way, publish/subscribe based on Redis is realized under .Net5. After
reading this article, it will be helpful to you, please help and like it.

Guess you like

Origin blog.csdn.net/paradoxx/article/details/115333885