- redis订阅发布:轻量级,低延迟,高并发,低可靠性
- 传统MQ,如rabbitmq:重量级,高可靠,异步,不保证实时
C# ServiceStack.Redis实现简单发布订阅
订阅客户端
static void Main(string[] args)
{
using (RedisClient consumer = new RedisClient("118.25.189.165", 6379, "XXXX"))
{
//创建订阅
IRedisSubscription subscription = consumer.CreateSubscription();
//接受到消息时
subscription.OnMessage = (channel, msg) =>
{
Console.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]") + " 频道:" + channel + " 消息:" + msg);
};
//订阅频道时
subscription.OnSubscribe = (channel) =>
{
Console.WriteLine("订阅客户端:开始订阅" + channel);
};
//取消订阅频道时
subscription.OnUnSubscribe = (a) => { Console.WriteLine("订阅客户端:取消订阅"); };
//订阅频道
subscription.SubscribeToChannels("channel1");
}
}
发布客户端
static void Main(string[] args)
{
Console.WriteLine("请输入发布的消息");
using (RedisClient client = new RedisClient("118.25.189.165", 6379, "XXXX"))
{
while (true)
{
string str = Console.ReadLine();
client.PublishMessage("channel1", str);
}
}
}