那么通过前面几篇博文,服务端的安装和配置应该没什么问题了,接下来的问题是如何通过代码来访问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 ///9 /// 密码 10 /// 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 /// 25 /// IP地址 26 /// 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 /// 41 /// 端口号 42 /// 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 /// 57 /// 链接超时时间 58 /// 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 /// 73 /// 重试次数 74 /// 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 /// 89 /// 默认使用的数据库(0 - 15) 90 /// 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 /// 105 /// 根据键名获取web.config/appsettings的值 106 /// 107 /// 键 108 /// 109 public static string GetAppWebConfig(string key) 110 { 111 string text = ConfigurationManager.AppSettings[key]; 112 return (text != null) ? text : string.Empty; 113 } 114 115 /// 116 /// Int类型转换 117 /// 118 /// 需要被转换的值 119 /// 转换失败后的默认值 120 /// 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 }
二.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 LazylazyConnection = new Lazy (() => 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 /// 36 /// Redis连接失败事件 37 /// 38 /// 39 /// 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 }
三.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 ///18 /// 构造函数,用于操作其他db 19 /// 20 /// 21 public RedisBase(int dbNumber) 22 { 23 db = RedisManager.Connection.GetDatabase(dbNumber); 24 } 25 26 27 /// 28 /// 设置String类型Redis缓存 29 /// 30 /// 关键字 31 /// String字符串 32 /// 过期时间 33 /// 34 public bool SetString(string key, string value, TimeSpan? expiry = default(TimeSpan?)) 35 { 36 return db.StringSet(key, value, expiry); 37 } 38 39 /// 40 /// 获取String类型Redis缓存 41 /// 42 /// 43 /// 44 public string GetString(string key) 45 { 46 return db.StringGet(key); 47 } 48 49 /// 50 /// 设置单个对象Redis缓存 51 /// 52 /// 53 /// 54 /// 55 /// 56 /// 57 public bool SetObject (string key, T value, TimeSpan? expiry = default(TimeSpan?)) where T : class 58 { 59 return SetString(key, JsonConvert.SerializeObject(value), expiry); 60 } 61 62 /// 63 /// 获取单个对象Redis缓存 64 /// 65 /// 66 /// 67 /// 68 public T GetObject (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 (value); 76 } 77 78 79 /// 80 /// 插入List集合对象 81 /// 82 /// 83 /// 84 /// 85 public bool SetList (string key, List value, TimeSpan? expiry = default(TimeSpan?)) 86 { 87 return SetString(key, JsonConvert.SerializeObject(value), expiry); 88 } 89 90 /// 91 /// 获取List集合对象 92 /// 93 /// 94 /// 95 /// 96 public List GetList (string key) 97 { 98 return JsonConvert.DeserializeObject >(GetString(key)); 99 } 100 101 ///
102 /// 删除单个Key 103 /// 104 /// 105 /// 106 public bool Remove(string key) 107 { 108 return db.KeyDelete(key); 109 } 110 111 /// 112 /// 删除多个key 113 /// 114 /// 115 public long RemoveAll(RedisKey[] keys) 116 { 117 return db.KeyDelete(keys); 118 } 119 120 121 /// 122 /// 判断key是否存在 123 /// 124 /// 125 /// 126 public bool ContainsKey(string key) 127 { 128 return db.KeyExists(key); 129 } 130 131 /// 132 /// 重新命名key 133 /// 134 /// 135 /// 136 /// 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 /// 147 /// 追加值 148 /// 149 /// 150 /// 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 }
作者:黄昌
出处:http://www.cnblogs.com/h-change/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。