人所缺乏的不是才干而是志向,不是成功的能力而是勤劳的意志。
订阅者
首先创建RedisClient
,然后调用CreateSubscription()
方法创建订阅客户端,然后设置订阅客户端的几个事件:
OnMessage
:接受到消息时。
OnSubscribe
:订阅频道时。
OnUnSubscribe
:取消订阅频道时。
最后,调用subscribeToChannels(channelName)
,订阅频道。
class Program
{
static void Main(string[] args)
{
Subscription();
}
public static void Subscription()
{
using (var consumer = new RedisClient("127.0.0.1", 6379, "123456"))
{
IRedisSubscription subscription = consumer.CreateSubscription();
subscription.OnMessage = (channel, msg) =>
{
Console.WriteLine("频道【" + channel + "】订阅客户端接收消息:" + ":" + msg + " [" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]");
Console.WriteLine("订阅数:" + subscription.SubscriptionCount);
Console.WriteLine("___________________________________________________________________");
};
subscription.OnSubscribe = channel => { Console.WriteLine("订阅客户端:开始订阅" + channel); };
subscription.OnUnSubscribe = a => { Console.WriteLine("订阅客户端:取消订阅"); };
subscription.SubscribeToChannels("channel-1");
}
}
}
发布者
首先创建RedisClient
,然后调用PublishMessage(channelName,message)
发布消息。
class Program
{
static void Main(string[] args)
{
using (IRedisClient publisher = new RedisClient("127.0.0.1", 6379, "123456"))
{
for (int i = 1; i <= 100; i++)
{
publisher.PublishMessage("channel-1", string.Format("这是我发送的第{0}消息!", i));
Thread.Sleep(200);
}
}
}
}
结果如图:


Redis
发布订阅 服务
class Program
{
static void Main(string[] args)
{
Pub();
Console.ReadLine();
}
#region Redis发布服务
public static void Pub()
{
IRedisClientsManager RedisClientManager = new PooledRedisClientManager("123456@127.0.0.1:6379");
var pubSubServer = new RedisPubSubServer(RedisClientManager, "channel-1", "channel-2");
pubSubServer.OnMessage = (channel, msg) =>
{
Console.WriteLine("【Redis发布服务APP】从频道{0}接收消息:{1} 时间:{2}", channel, msg, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
Console.WriteLine("___________________________________________________________________");
};
pubSubServer.OnStart = () =>
{
Console.WriteLine("发布服务已启动");
Console.WriteLine("___________________________________________________________________");
};
pubSubServer.OnStop = () => { Console.WriteLine("服务停止"); };
pubSubServer.OnUnSubscribe = channel =>
{
Console.WriteLine(channel);
};
pubSubServer.OnError = e => { Console.WriteLine(e.Message); };
pubSubServer.OnFailover = s => { Console.WriteLine(s); };
pubSubServer.Start();
}
#endregion
}
当运行发布者,此发布订阅服务程序执行如图:
