Fork me on GitHub

.net redis 发布订阅demo

发布者:

using StackExchange.Redis;
using System;

namespace publish
{
class Program
{
static void Main(string[] args)
{
//创建连接
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");
}
}
}
}


订阅者:

using StackExchange.Redis;
using System;

namespace subscription
{
class Program
{
static void Main(string[] args)
{
//创建连接
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();
}
}
}
}

posted @ 2021-08-03 18:01  WantRemake  阅读(108)  评论(0编辑  收藏  举报