码迷,mamicode.com
首页 > Windows程序 > 详细

5.C#编写Redis访问类

时间:2017-03-27 00:48:17      阅读:644      评论:0      收藏:0      [点我收藏+]

标签:created   point   dbn   字符串   row   connected   failure   res   setting   

那么通过前面几篇博文,服务端的安装和配置应该没什么问题了,接下来的问题是如何通过代码来访问Redis。

这里我们使用的库为:

StackExchange.Redis

GitHub:https://github.com/StackExchange/StackExchange.Redis

NuGet:PM> Install-Package StackExchange.Redis

Newtonsoft.Json(Json.NET)

GitHub:https://github.com/JamesNK/Newtonsoft.Json

NuGet:PM> Install-Package Newtonsoft.Json

如果你项目中有Newtonsoft.Json可以不用安装

一.Redis配置类(RedisConfig.cs),用于配置Redis的参数

技术分享
  1 using System.Configuration;
  2 
  3 namespace RedisDemo.Common
  4 {
  5     public static class RedisConfig
  6     {
  7         private static string _Password = string.Empty;
  8         /// <summary>
  9         /// 密码
 10         /// </summary>
 11         public static string Password
 12         {
 13             get
 14             {
 15                 if (string.IsNullOrEmpty(_Password))
 16                 {
 17                     _Password = GetAppWebConfig("RedisPassword");
 18                 }
 19                 return _Password;
 20             }
 21         }
 22 
 23         private static string _IP = string.Empty;
 24         /// <summary>
 25         /// IP地址
 26         /// </summary>
 27         public static string IP
 28         {
 29             get
 30             {
 31                 if (string.IsNullOrEmpty(_IP))
 32                 {
 33                     _IP = GetAppWebConfig("RedisIP");
 34                 }
 35                 return _IP;
 36             }
 37         }
 38 
 39         private static int _Port = 0;
 40         /// <summary>
 41         /// 端口号
 42         /// </summary>
 43         public static int Port
 44         {
 45             get
 46             {
 47                 if (_Port == 0)
 48                 {
 49                     _Port = ParseInt(GetAppWebConfig("RedisPort"), 6379);
 50                 }
 51                 return _Port;
 52             }
 53         }
 54 
 55         private static int _Timeout = 0;
 56         /// <summary>
 57         /// 链接超时时间
 58         /// </summary>
 59         public static int Timeout
 60         {
 61             get
 62             {
 63                 if (_Timeout == 0)
 64                 {
 65                     _Timeout = ParseInt(GetAppWebConfig("RedisTimeout"), 10000);
 66                 }
 67                 return _Timeout;
 68             }
 69         }
 70 
 71         private static int _Retry = 0;
 72         /// <summary>
 73         /// 重试次数
 74         /// </summary>
 75         public static int Retry
 76         {
 77             get
 78             {
 79                 if (_Retry == 0)
 80                 {
 81                     _Retry = ParseInt(GetAppWebConfig("RedisRetry"), 3);
 82                 }
 83                 return _Retry;
 84             }
 85         }
 86 
 87         private static int _DefaultDB = -1;
 88         /// <summary>
 89         /// 默认使用的数据库(0 - 15)
 90         /// </summary>
 91         public static int DefaultDB
 92         {
 93             get
 94             {
 95                 if (_DefaultDB == -1)
 96                 {
 97                     _DefaultDB = ParseInt(GetAppWebConfig("RedisDefaultDB"), 0);
 98                 }
 99                 return _DefaultDB;
100             }
101         }
102 
103 
104         /// <summary>
105         /// 根据键名获取web.config/appsettings的值
106         /// </summary>
107         /// <param name="key"></param>
108         /// <returns></returns>
109         public static string GetAppWebConfig(string key)
110         {
111             string text = ConfigurationManager.AppSettings[key];
112             return (text != null) ? text : string.Empty;
113         }
114 
115         /// <summary>
116         /// Int类型转换
117         /// </summary>
118         /// <param name="o">需要被转换的值</param>
119         /// <param name="defaultVal">转换失败后的默认值</param>
120         /// <returns></returns>
121         public static int ParseInt(object o, int defaultVal)
122         {
123             int result;
124             if (o == null)
125             {
126                 result = defaultVal;
127             }
128             else
129             {
130                 string s = o.ToString();
131                 int num;
132                 if (!int.TryParse(s, out num))
133                 {
134                     num = defaultVal;
135                 }
136                 result = num;
137             }
138             return result;
139         }
140     }
141 }
View Code

 

二.Redis连接管理类(RedisManager.cs)

技术分享
  1 using Newtonsoft.Json;
  2 using StackExchange.Redis;
  3 using System;
  4 using System.IO;
  5 using System.Text;
  6 using System.Web;
  7 
  8 namespace RedisDemo.Common
  9 {
 10     public class RedisManager
 11     {
 12         private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
 13         {
 14             var configurationOptions = new ConfigurationOptions()
 15             {
 16                 Password = RedisConfig.Password,
 17                 EndPoints = { { RedisConfig.IP, RedisConfig.Port } },
 18                 DefaultDatabase = RedisConfig.DefaultDB,
 19                 ConnectTimeout = RedisConfig.Timeout,
 20                 ConnectRetry = RedisConfig.Retry,
 21                 AbortOnConnectFail = false
 22             };
 23             return ConnectionMultiplexer.Connect(configurationOptions);
 24         });
 25 
 26         public static ConnectionMultiplexer Connection
 27         {
 28             get
 29             {
 30                 return lazyConnection.Value;
 31             }
 32         }
 33 
 34 
 35         /// <summary>
 36         /// Redis连接失败事件
 37         /// </summary>
 38         /// <param name="sender"></param>
 39         /// <param name="e"></param>
 40         private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
 41         {
 42             var faildObj = new
 43             {
 44                 EndPoint = e.EndPoint.ToString(),
 45                 FailureType = e.FailureType.ToString(),
 46                 Message = e.Exception == null ? "" : e.Exception.Message
 47             };
 48             string logText = string.Format(LOG_ERROR_TEMPLATE, DateTime.Now, "Redis连接失败", JsonConvert.SerializeObject(faildObj));
 49             WriteRedisErrorLog(logText);
 50         }
 51 
 52         private static void WriteRedisErrorLog(string Content)
 53         {
 54             DateTime logDate = DateTime.Now;
 55             string logPath = "~/Log/RedisError/";
 56             string logFilePath = GetMapPath(logPath + logDate.ToString("yyyy") + "/" + logDate.ToString("MM") + "/" + logDate.ToString("yyyyMMdd") + ".log");
 57             WriteFile(logFilePath, Content, true);
 58         }
 59 
 60 
 61         private const string LOG_ERROR_TEMPLATE = "**************** {0} ****************\r\n"
 62                                                 + "类型:{1}\r\n\r\n"
 63                                                 + "消息:{2}\r\n\r\n\r\n\r\n\r\n\r\n";
 64 
 65         private static void WriteFile(string file, string fileContent, bool Append)
 66         {
 67             FileInfo fileInfo = new FileInfo(file);
 68             if (!Directory.Exists(fileInfo.DirectoryName))
 69             {
 70                 Directory.CreateDirectory(fileInfo.DirectoryName);
 71             }
 72             StreamWriter streamWriter = new StreamWriter(file, Append, Encoding.UTF8);
 73             try
 74             {
 75                 streamWriter.Write(fileContent);
 76             }
 77             catch (Exception ex)
 78             {
 79                 throw new Exception(ex.ToString());
 80             }
 81             finally
 82             {
 83                 streamWriter.Flush();
 84                 streamWriter.Close();
 85             }
 86         }
 87 
 88         public static string GetMapPath(string strPath)
 89         {
 90             string result;
 91             if (HttpContext.Current != null)
 92             {
 93                 result = HttpContext.Current.Server.MapPath(strPath);
 94             }
 95             else
 96             {
 97                 result = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath.TrimStart(~, /));
 98             }
 99             return result;
100         }
101     }
102 }
View Code

 

三.Redis操作类(RedisBase.cs)

技术分享
  1 using Newtonsoft.Json;
  2 using StackExchange.Redis;
  3 using System;
  4 using System.Collections.Generic;
  5 
  6 namespace RedisDemo.Common
  7 {
  8     public class RedisBase
  9     {
 10         IDatabase db;
 11 
 12         public RedisBase()
 13         {
 14             db = RedisManager.Connection.GetDatabase();
 15         }
 16 
 17         /// <summary>
 18         /// 构造函数,用于操作其他db
 19         /// </summary>
 20         /// <param name="dbNumber"></param>
 21         public RedisBase(int dbNumber)
 22         {
 23             db = RedisManager.Connection.GetDatabase(dbNumber);
 24         }
 25 
 26 
 27         /// <summary>
 28         /// 设置String类型Redis缓存
 29         /// </summary>
 30         /// <param name="key">关键字</param>
 31         /// <param name="value">String字符串</param>
 32         /// <param name="expiry">过期时间</param>
 33         /// <returns></returns>
 34         public bool SetString(string key, string value, TimeSpan? expiry = default(TimeSpan?))
 35         {
 36             return db.StringSet(key, value, expiry);
 37         }
 38 
 39         /// <summary>
 40         /// 获取String类型Redis缓存
 41         /// </summary>
 42         /// <param name="key"></param>
 43         /// <returns></returns>
 44         public string GetString(string key)
 45         {
 46             return db.StringGet(key);
 47         }
 48 
 49         /// <summary>
 50         /// 设置单个对象Redis缓存
 51         /// </summary>
 52         /// <typeparam name="T"></typeparam>
 53         /// <param name="key"></param>
 54         /// <param name="value"></param>
 55         /// <param name="expiry"></param>
 56         /// <returns></returns>
 57         public bool SetObject<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?)) where T : class
 58         {
 59             return SetString(key, JsonConvert.SerializeObject(value), expiry);
 60         }
 61 
 62         /// <summary>
 63         /// 获取单个对象Redis缓存
 64         /// </summary>
 65         /// <typeparam name="T"></typeparam>
 66         /// <param name="key"></param>
 67         /// <returns></returns>
 68         public T GetObject<T>(string key) where T : class
 69         {
 70             string value = GetString(key);
 71             if (string.IsNullOrEmpty(value))
 72             {
 73                 return null;
 74             }
 75             return JsonConvert.DeserializeObject<T>(value);
 76         }
 77 
 78 
 79         /// <summary>
 80         /// 插入List集合对象
 81         /// </summary>
 82         /// <typeparam name="T"></typeparam>
 83         /// <param name="key"></param>
 84         /// <param name="value"></param>
 85         public bool SetList<T>(string key, List<T> value, TimeSpan? expiry = default(TimeSpan?))
 86         {
 87             return SetString(key, JsonConvert.SerializeObject(value), expiry);
 88         }
 89 
 90         /// <summary>
 91         /// 获取List集合对象
 92         /// </summary>
 93         /// <typeparam name="T"></typeparam>
 94         /// <param name="key"></param>
 95         /// <returns></returns>
 96         public List<T> GetList<T>(string key)
 97         {
 98             return JsonConvert.DeserializeObject<List<T>>(GetString(key));
 99         }
100 
101         /// <summary>
102         /// 删除单个Key
103         /// </summary>
104         /// <param name="key"></param>
105         /// <returns></returns>
106         public bool Remove(string key)
107         {
108             return db.KeyDelete(key);
109         }
110 
111         /// <summary>
112         /// 删除多个key
113         /// </summary>
114         /// <param name="keys"></param>
115         public long RemoveAll(RedisKey[] keys)
116         {
117             return db.KeyDelete(keys);
118         }
119 
120 
121         /// <summary>
122         /// 判断key是否存在
123         /// </summary>
124         /// <param name="key"></param>
125         /// <returns></returns>
126         public bool ContainsKey(string key)
127         {
128             return db.KeyExists(key);
129         }
130 
131         /// <summary>
132         /// 重新命名key
133         /// </summary>
134         /// <param name="key"></param>
135         /// <param name="newKey"></param>
136         /// <returns></returns>
137         public bool KeyRename(string key, string newKey)
138         {
139             if (!this.ContainsKey(key))
140             {
141                 return false;
142             }
143             return db.KeyRename(key, newKey);
144         }
145 
146         /// <summary>
147         /// 追加值
148         /// </summary>
149         /// <param name="key"></param>
150         /// <param name="value"></param>
151         public void AppendString(string key, string value)
152         {
153             //追加值,返回追加后长度
154             long appendlong = db.StringAppend(key, value);
155         }
156 
157         public bool IsConnected(RedisKey key)
158         {
159             return db.IsConnected(key, CommandFlags.None);
160         }
161     }
162 }
View Code

 

作者:黄昌
出处:http://www.cnblogs.com/h-change/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

5.C#编写Redis访问类

标签:created   point   dbn   字符串   row   connected   failure   res   setting   

原文地址:http://www.cnblogs.com/h-change/p/6624690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!