[Redis]发布/订阅
摘要
有这样的一个场景,管理员需要发布一条消息,所有的客户端都要受到通知。然后想到了发布订阅模式。使用redis的发布与订阅实现起来更简单一些,说做就做,这里弄个简单的demo,先模拟下。
核心代码
首先使用Nuget安装redis程序集。
服务端发布消息webApi
向频道chanel-1 发送消息。
public class MessageController : ApiController
{
[HttpGet]
[Route("api/send/{msg}")]
public HttpResponseMessage SendMessage(string msg)
{
IRedisClientsManager clientManager = new PooledRedisClientManager("password@192.168.1.102:6379");
var client = clientManager.GetClient();
client.PublishMessage("channel-1", msg);
return new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _msg = "Success" })) };
}
}
订阅客户端代码
class Program
{
static void Main(string[] args)
{
Subscript();
Console.Read();
}
/// <summary>
/// 订阅
/// </summary>
public static void Subscript()
{
IRedisClientsManager clientManager = new PooledRedisClientManager("password@192.168.1.102:6379");
var client = clientManager.GetClient();
//创建订阅
IRedisSubscription subscription = client.CreateSubscription();
//接收消息处理Action
subscription.OnMessage = (channel, msg) =>
{
Console.WriteLine("频道【{0}】[{1}]", channel, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine(msg);
};
//订阅事件处理
subscription.OnSubscribe = (channel) =>
{
Console.WriteLine("订阅客户端:开始订阅" + channel);
};
//取消订阅事件处理
subscription.OnUnSubscribe = (a) => { Console.WriteLine("订阅客户端:取消订阅"); };
//订阅频道
subscription.SubscribeToChannels("channel-1");
}
}
}
测试
通过postman调用接口,开启订阅客户端。
订阅的客户端
结语
发现通过这种方式实现的发布与订阅还是很简单的。
转载:博客地址:http://www.cnblogs.com/wolf-sun/