using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using ServiceStack.Common;
using System.Threading;
namespace RedisTest2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("請輸入釋出訂閱類型?");
var type = Console.ReadLine();
if (type == "pub")
{
Pub();
}
else
{
Sub();
}
}
public static void Pub()
{
using (IRedisClient publisher = new RedisClient("127.0.0.1", 6379))
{
while (true)
{
var msg = Console.ReadKey();
publisher.PublishMessage("c1", string.Format("這是我發送的第消息!{0}", DateTime.Now));
}
}
//using (IRedisClient publisher = new RedisClient("127.0.0.1", 6379))
//{
// //for (int i = 1; i <= 100; i++)
// //{
// while (true)
// {
// publisher.PublishMessage("c1", string.Format("這是我發送的第消息!{0}", DateTime.Now));
// }
// // Thread.Sleep(200);
// // }
//}
}
/// <summary>
/// 訂閱
/// 一個用戶端訂閱c1
/// </summary>
public static void Sub()
{
using (var consumer = new RedisClient("127.0.0.1", 6379))
{
//建立訂閱
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("訂閱用戶端a:開始訂閱" + channel); };
//取消訂閱事件處理
subscription.OnUnSubscribe = a => { Console.WriteLine("訂閱用戶端:取消訂閱"); };
//訂閱頻道
subscription.SubscribeToChannels("c1");
}
}
}
}
View Code