那麼經過前面幾篇博文,服務端的安裝和配置應該沒什麼問題了,接下來的問題是如何經過代碼來訪問Redis。git
這裏咱們使用的庫爲:github
StackExchange.Redisweb
GitHub:https://github.com/StackExchange/StackExchange.Redis數據庫
NuGet:PM> Install-Package StackExchange.Redis緩存
Newtonsoft.Json(Json.NET)app
GitHub:https://github.com/JamesNK/Newtonsoft.Jsonide
NuGet:PM> Install-Package Newtonsoft.Json函數
若是你項目中有Newtonsoft.Json能夠不用安裝this
一.Redis配置類(RedisConfig.cs),用於配置Redis的參數spa
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 }
二.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 }
三.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 }
做者:黃昌出處:http://www.cnblogs.com/h-change/本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文連接,不然保留追究法律責任的權利。