0.引入.net core環境下Redis的NuGet包,StackExchange.Redis,現目前最新的2.0.519。 1 using System; 2 using System.Collections.Generic; 3 using StackExchange.Redis; 4 usi ...
0.引入.net core環境下Redis的NuGet包,StackExchange.Redis,現目前最新的2.0.519。
- 幫助類Code:
1 using System; 2 using System.Collections.Generic; 3 using StackExchange.Redis; 4 using Newtonsoft.Json; 5 using YJT.Web.lib; 6 using YJT.Common.Log; 7 8 namespace YJT.Web.Redis 9 { 10 /// <summary> 11 /// Redis幫助類 12 /// </summary> 13 public class RedisHelper 14 { 15 //單例模式 16 public static RedisCommon Default { get { return new RedisCommon(); } } 17 public static RedisCommon One { get { return new RedisCommon(1, UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"); } } 18 public static RedisCommon Two { get { return new RedisCommon(2, UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"); } } 19 public static RedisCommon Three { get { return new RedisCommon(3, UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"); } } 20 } 21 22 /// <summary> 23 /// Redis操作類 24 /// 老版用的是ServiceStack.Redis 25 /// .Net Core使用StackExchange.Redis的nuget包 26 /// </summary> 27 public class RedisCommon 28 { 29 //redis資料庫連接字元串 30 private string _conn = UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6789"; 31 private int _db = 0; 32 33 //靜態變數 保證各模塊使用的是不同實例的相同鏈接 34 private static ConnectionMultiplexer connection; 35 36 /// <summary> 37 /// 構造函數 38 /// </summary> 39 public RedisCommon() { } 40 /// <summary> 41 /// 構造函數 42 /// </summary> 43 /// <param name="db"></param> 44 /// <param name="connectStr"></param> 45 public RedisCommon(int db, string connectStr) 46 { 47 _db = db; 48 _conn = connectStr; 49 } 50 51 /// <summary> 52 /// 緩存資料庫,資料庫連接 53 /// </summary> 54 public ConnectionMultiplexer CacheConnection 55 { 56 get 57 { 58 try 59 { 60 if (connection == null || !connection.IsConnected) 61 { 62 connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_conn)).Value; 63 } 64 } 65 catch (Exception ex) 66 { 67 Log.Debug("RedisHelper->CacheConnection 出錯\r\n", ex.Message.ToString()); 68 return null; 69 } 70 return connection; 71 } 72 } 73 74 /// <summary> 75 /// 緩存資料庫 76 /// </summary> 77 public IDatabase CacheRedis => CacheConnection.GetDatabase(_db); 78 79 80 #region --KEY/VALUE存取-- 81 /// <summary> 82 /// 單條存值 83 /// </summary> 84 /// <param name="key">key</param> 85 /// <param name="value">The value.</param> 86 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> 87 public bool StringSet(string key, string value) 88 { 89 return CacheRedis.StringSet(key, value); 90 } 91 92 /// <summary> 93 /// 保存單個key value 94 /// </summary> 95 /// <param name="key">Redis Key</param> 96 /// <param name="value">保存的值</param> 97 /// <param name="expiry">過期時間</param> 98 /// <returns></returns> 99 public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?)) 100 { 101 return CacheRedis.StringSet(key, value, expiry); 102 } 103 104 /// <summary> 105 /// 保存多個key value 106 /// </summary> 107 /// <param name="arr">key</param> 108 /// <returns></returns> 109 public bool StringSet(KeyValuePair<RedisKey, RedisValue>[] arr) 110 { 111 return CacheRedis.StringSet(arr); 112 } 113 114 /// <summary> 115 /// 批量存值 116 /// </summary> 117 /// <param name="keysStr">key</param> 118 /// <param name="valuesStr">The value.</param> 119 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> 120 public bool StringSetMany(string[] keysStr, string[] valuesStr) 121 { 122 var count = keysStr.Length; 123 var keyValuePair = new KeyValuePair<RedisKey, RedisValue>[count]; 124 for (int i = 0; i < count; i++) 125 { 126 keyValuePair[i] = new KeyValuePair<RedisKey, RedisValue>(keysStr[i], valuesStr[i]); 127 } 128 129 return CacheRedis.StringSet(keyValuePair); 130 } 131 132 /// <summary> 133 /// 保存一個對象 134 /// </summary> 135 /// <typeparam name="T"></typeparam> 136 /// <param name="key"></param> 137 /// <param name="obj"></param> 138 /// <returns></returns> 139 public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?)) 140 { 141 string json = JsonConvert.SerializeObject(obj); 142 return CacheRedis.StringSet(key, json, expiry); 143 } 144 145 /// <summary> 146 /// 追加值 147 /// </summary> 148 /// <param name="key"></param> 149 /// <param name="value"></param> 150 public void StringAppend(string key, string value) 151 { 152 ////追加值,返回追加後長度 153 long appendlong = CacheRedis.StringAppend(key, value); 154 } 155 156 /// <summary> 157 /// 獲取單個key的值 158 /// </summary> 159 /// <param name="key">Redis Key</param> 160 /// <returns></returns> 161 public RedisValue GetStringKey(string key) 162 { 163 return CacheRedis.StringGet(key); 164 } 165 166 /// <summary> 167 /// 根據Key獲取值 168 /// </summary> 169 /// <param name="key">鍵值</param> 170 /// <returns>System.String.</returns> 171 public string StringGet(string key) 172 { 173 try 174 { 175 return CacheRedis.StringGet(key); 176 } 177 catch (Exception ex) 178 { 179 Log.Debug("RedisHelper->StringGet 出錯\r\n", ex.Message.ToString()); 180 return null; 181 } 182 } 183 184 /// <summary> 185 /// 獲取多個Key 186 /// </summary> 187 /// <param name="listKey">Redis Key集合</param> 188 /// <returns></returns> 189 public RedisValue[] GetStringKey(List<RedisKey> listKey) 190 { 191 return CacheRedis.StringGet(listKey.ToArray()); 192 } 193 194 /// <summary> 195 /// 批量獲取值 196 /// </summary> 197 public string[] StringGetMany(string[] keyStrs) 198 { 199 var count = keyStrs.Length; 200 var keys = new RedisKey[count]; 201 var addrs = new string[count]; 202 203 for (var i = 0; i < count; i++) 204 { 205 keys[i] = keyStrs[i]; 206 } 207 try 208 { 209 210 var values = CacheRedis.StringGet(keys); 211 for (var i = 0; i < values.Length; i++) 212 { 213 addrs[i] = values[i]; 214 } 215 return addrs; 216 } 217 catch (Exception ex) 218 { 219 Log.Debug("RedisHelper->StringGetMany 出錯\r\n", ex.Message.ToString()); 220 return null; 221 } 222 } 223 224 /// <summary> 225 /// 獲取一個key的對象 226 /// </summary> 227 /// <typeparam name="T"></typeparam> 228 /// <param name="key"></param> 229 /// <returns></returns> 230 public T GetStringKey<T>(string key) 231 { 232 return JsonConvert.DeserializeObject<T>(CacheRedis.StringGet(key)); 233 } 234 #endregion 235 236 237 #region --刪除設置過期-- 238 /// <summary> 239 /// 刪除單個key 240 /// </summary> 241 /// <param name="key">redis key</param> 242 /// <returns>是否刪除成功</returns> 243 public bool KeyDelete(string key) 244 { 245 return CacheRedis.KeyDelete(key); 246 } 247 248 /// <summary> 249 /// 刪除多個key 250 /// </summary> 251 /// <param name="keys">rediskey</param> 252 /// <returns>成功刪除的個數</returns> 253 public long KeyDelete(RedisKey[] keys) 254 { 255 return CacheRedis.KeyDelete(keys); 256 } 257 258 /// <summary> 259 /// 判斷key是否存儲 260 /// </summary> 261 /// <param name="key">redis key</param> 262 /// <returns></returns> 263 public bool KeyExists(string key) 264 { 265 return CacheRedis.KeyExists(key); 266 } 267 268 /// <summary> 269 /// 重新命名key 270 /// </summary> 271 /// <param name="key">就的redis key</param> 272 /// <param name="newKey">新的redis key</param> 273 /// <returns></returns> 274 public bool KeyRename(string key, string newKey) 275 { 276 return CacheRedis.KeyRename(key, newKey); 277 } 278 279 /// <summary> 280 /// 刪除hasekey 281 /// </summary> 282 /// <param name="key"></param> 283 /// <param name="hashField"></param> 284 /// <returns></returns> 285 public bool HaseDelete(RedisKey key, RedisValue hashField) 286 { 287 return CacheRedis.HashDelete(key, hashField); 288 } 289 290 /// <summary> 291 /// 移除hash中的某值 292 /// </summary> 293 /// <typeparam name="T"></typeparam> 294 /// <param name="key"></param> 295 /// <param name="dataKey"></param> 296 /// <returns></returns> 297 public bool HashRemove(string key, string dataKey) 298 { 299 return CacheRedis.HashDelete(key, dataKey); 300 } 301 302 /// <summary> 303 /// 設置緩存過期 304 /// </summary> 305 /// <param name="key"></param> 306 /// <param name="datetime"></param> 307 public void SetExpire(string key, DateTime datetime) 308 { 309 CacheRedis.KeyExpire(key, datetime); 310 } 311 #endregion 312 } 313 }
View Code - using引用備註:
using Newtonsoft.Json;//為第三方轉json 對象使用的,再熟悉不過了吧
using YJT.Common.Log;//是一個記錄日誌的幫助的類,你可以用你自己的來記錄日誌。
using YJT.Web.lib;//此引用是獲取.net core中的appsettings.json中配置的信息。 UtilConf.Configuration["RedisConfig:ReadWriteHosts"]獲取 - 獲取appsettings.json的UtilConf.cs幫助類:
1 using Microsoft.Extensions.Configuration; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Text; 6 7 namespace YJT.Web.lib 8 { 9 /// <summary> 10 /// 讀配置文件 11 /// </summary> 12 public class UtilConf 13 { 14 private static IConfiguration config; 15 16 /// <summary> 17 /// 載入配置文件 18 /// </summary> 19 public static IConfiguration Configuration 20 { 21 get 22 { 23 if (config != null) return config; 24 config = new ConfigurationBuilder() 25 .SetBasePath(Directory.GetCurrentDirectory()) 26 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 27 .Build(); 28 return config; 29 } 30 set => config = value; 31 } 32 } 33 }
View Code此類主要是獲取.net core 中的json配置信息。如:UtilConf.Configuration["RedisConfig:ReadWriteHosts"]
- StackExchange.Redis下的IDatabase介面還有豐富的操作方法,可自行研究補充幫助類
分享至此,歡迎留言評論~~~