trzxycx 发表于 2017-12-20 14:59:22

.net core 使用Redis的发布订阅

  Redis是一个性能非常强劲的内存数据库,它一般是作为缓存来使用,但是他不仅仅可以用来作为缓存,比如著名的分布式框架dubbo就可以用Redis来做服务注册中心。接下来介绍一下.net core 使用Redis的发布/订阅功能。

Redis 发布订阅
  Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
  
Redis 客户端可以订阅任意数量的通道。
  下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:

  当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:


使用Redis命令
  首先,通过subscribe redismessage命令使两个客户端订阅redismessage通道:

  然后再打开一个Redis客户端,使用命令publish redismessage "消息内容"发布消息


使用.net core 实现
  这里我选择的连接驱动为 StackExchange.Redis,这里需要注意的是 ServiceStack.Redis连接驱动已经逐渐商业化,4.0及以上版本都具有限制,所以选择的免费且好用的StackExchange.Redis,使用nuget安装即可。

建立订阅客户端
  

//创建连接  
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");
  
}
  

  下面运行了一个发布客户端,两个订阅客户端:

  Demo下载
页: [1]
查看完整版本: .net core 使用Redis的发布订阅