Redis可以作为数据库,提供高速缓存,消息队列等功能,这里介绍Redis可以做的其中两件事:
1.提供缓存功能,作为缓存服务器;
2.轻量级的消息队列(MQ)进行使用.
/// <summary> /// Redis帮助类 /// </summary> public class RedisHelper { /// <summary> /// 往消息队列中放入数据 /// </summary> /// <param name="listId">队列Id</param> /// <param name="value">数据</param> public static void Enqueue(string listId, string value) { using (IRedisClient client = RedisManager.ClientManager.GetClient()) { client.EnqueueItemOnList(listId, value); } return; } /// <summary> /// 从消息队列中取出数据 /// </summary> /// <param name="listId">队列Id</param> /// <returns></returns> public static string Dequeue(string listId) { using (IRedisClient client = RedisManager.ClientManager.GetClient()) { return client.DequeueItemFromList(listId); } } /// <summary> /// 从消息队列中取出数据 /// </summary> /// <param name="redisClient"></param> /// <param name="listId"></param> /// <returns></returns> public static string Dequeue(IRedisClient redisClient, string listId) { return redisClient.DequeueItemFromList(listId); } /// <summary> /// Redis写 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="cacheTime">缓存时间(分钟)</param> /// <returns></returns> public static bool Set<T>(string key, T value, int cacheTime = 0) { using (IRedisClient client = RedisManager.ClientManager.GetClient()) { if (cacheTime <= 0) { return client.Set<T>(key, value); } return client.Set<T>(key, value, DateTime.Now.AddMinutes(cacheTime)); } } /// <summary> /// Redis读 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <returns></returns> public static T Get<T>(string key) { using (IRedisClient client = RedisManager.ClientManager.GetClient()) { return client.Get<T>(key); } } } /// <summary> /// Redis管理类 /// </summary> public class RedisManager { public static PooledRedisClientManager ClientManager { get; private set; } static RedisManager() { RedisClientManagerConfig redisConfig = new RedisClientManagerConfig(); redisConfig.MaxWritePoolSize = 128; redisConfig.MaxReadPoolSize = 128; ClientManager = new PooledRedisClientManager(new string[] { "127.0.0.1" }, new string[] { "127.0.0.1" }, redisConfig); } }
消息队列数据消费方示例代码:
JavaScriptSerializer serializer = new JavaScriptSerializer(); //数据消费者 while (true) { string data = RedisHelper.Dequeue("sendActiveEmail"); if (data != null) { EmailModel emailModel = (EmailModel)serializer.Deserialize(data, typeof(EmailModel)); Console.WriteLine("发送邮件:" + emailModel.MailTo); CommonHelper.SendEmail(emailModel.MailTo, emailModel.Subject, emailModel.Body, true); Console.WriteLine("发送邮件完成"); } else { Thread.Sleep(500); } }
附:
Redis驱动开发包(.dll):