前面三节介绍了Redis的安装,Redis主从,Redis集群
该章节介绍Redis C#中的应用 实例:在主服务器写入一个字符串,在从服务器读取字符串
1 public sealed class RedisConfigInfo : ConfigurationSection 2 { 3 /// <summary> 4 /// 获取配置信息 5 /// </summary> 6 /// <returns></returns> 7 public static RedisConfigInfo GetConfig() 8 { 9 return GetConfig("redisconfig"); 10 } 11 /// <summary> 12 /// 获取配置信息 13 /// </summary> 14 /// <param name="sectionName">xml节点名称</param> 15 /// <returns></returns> 16 public static RedisConfigInfo GetConfig(string sectionName) 17 { 18 RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection(sectionName); 19 if (section == null) 20 throw new ConfigurationErrorsException("Section " + sectionName + " is not found."); 21 return section; 22 } 23 /// <summary> 24 /// 可写的Redis链接地址 25 /// </summary> 26 [ConfigurationProperty("WriteServerList", IsRequired = false)] 27 public string WriteServerList 28 { 29 get 30 { 31 return (string)base["WriteServerList"]; 32 } 33 set 34 { 35 base["WriteServerList"] = value; 36 } 37 } 38 /// <summary> 39 /// 可读的Redis链接地址 40 /// </summary> 41 [ConfigurationProperty("ReadServerList", IsRequired = false)] 42 public string ReadServerList 43 { 44 get 45 { 46 return (string)base["ReadServerList"]; 47 } 48 set 49 { 50 base["ReadServerList"] = value; 51 } 52 } 53 /// <summary> 54 /// 最大写链接数 55 /// </summary> 56 [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)] 57 public int MaxWritePoolSize 58 { 59 get 60 { 61 int _maxWritePoolSize = (int)base["MaxWritePoolSize"]; 62 return _maxWritePoolSize > 0 ? _maxWritePoolSize : 5; 63 } 64 set 65 { 66 base["MaxWritePoolSize"] = value; 67 } 68 } 69 /// <summary> 70 /// 最大读链接数 71 /// </summary> 72 [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)] 73 public int MaxReadPoolSize 74 { 75 get 76 { 77 int _maxReadPoolSize = (int)base["MaxReadPoolSize"]; 78 return _maxReadPoolSize > 0 ? _maxReadPoolSize : 5; 79 } 80 set 81 { 82 base["MaxReadPoolSize"] = value; 83 } 84 } 85 /// <summary> 86 /// 自动重启 87 /// </summary> 88 [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)] 89 public bool AutoStart 90 { 91 get 92 { 93 return (bool)base["AutoStart"]; 94 } 95 set 96 { 97 base["AutoStart"] = value; 98 } 99 } 100 /// <summary> 101 /// 本地缓存到期时间,单位:秒 102 /// </summary> 103 [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)] 104 public int LocalCacheTime 105 { 106 get 107 { 108 return (int)base["LocalCacheTime"]; 109 } 110 set 111 { 112 base["LocalCacheTime"] = value; 113 } 114 } 115 /// <summary> 116 /// 是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项 117 /// </summary> 118 [ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)] 119 public bool RecordeLog 120 { 121 get 122 { 123 return (bool)base["RecordeLog"]; 124 } 125 set 126 { 127 base["RecordeLog"] = value; 128 } 129 } 130 /// <summary> 131 /// 默认开始db 132 /// </summary> 133 [ConfigurationProperty("DefaultDb", IsRequired = false)] 134 public long DefaultDb 135 { 136 get 137 { 138 return (long)base["DefaultDb"]; 139 } 140 set 141 { 142 base["DefaultDb"] = value; 143 } 144 } 145 146 }
1 <?xml version="1.0" encoding="utf-8"?> 2 <redisconfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" MaxWritePoolSize="60" MaxReadPoolSize="60" AutoStart="true" LocalCacheTime="180" RecordeLog="false"></redisconfig>
1 public class RedisCache 2 { 3 #region -- 连接信息 -- 4 /// <summary> 5 /// redis配置文件信息 6 /// </summary> 7 private static RedisConfigInfo redisConfigInfo = RedisConfigInfo.GetConfig(); 8 /// <summary> 9 /// 创建链接池管理对象 10 /// </summary> 11 private static PooledRedisClientManager CreateManager(long dbId) 12 { 13 string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ","); 14 string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ","); 15 16 return new PooledRedisClientManager(readServerList, writeServerList, 17 new RedisClientManagerConfig 18 { 19 MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize, 20 MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize, 21 AutoStart = redisConfigInfo.AutoStart, 22 DefaultDb = dbId 23 }); 24 } 25 /// <summary> 26 /// 字串转数组 27 /// </summary> 28 /// <param name="strSource">字串</param> 29 /// <param name="split">分隔符</param> 30 /// <returns></returns> 31 private static string[] SplitString(string strSource, string split) 32 { 33 return strSource.Split(split.ToArray()); 34 } 35 /// <summary> 36 /// 获取redis客户端根据库ID号 37 /// </summary> 38 /// <param name="dbId">redis库Id</param> 39 /// <returns></returns> 40 private static PooledRedisClientManager GetClientManager(long dbId) 41 { 42 return CreateManager(dbId); 43 } 44 45 #endregion 46 47 #region -- Item -- 48 /// <summary> 49 /// 设置单体 50 /// </summary> 51 /// <typeparam name="T">值类型</typeparam> 52 /// <param name="key">键值</param> 53 /// <param name="t">值</param> 54 /// <param name="dbId">库Id</param> 55 /// <returns></returns> 56 public static bool Set<T>(string key, T t, long dbId = 0) 57 { 58 var clientManager = GetClientManager(dbId); 59 IRedisClient redis = clientManager.GetClient(); 60 var res = redis.Set<T>(key, t); 61 clientManager.DisposeClient((RedisNativeClient)redis); 62 redis.Dispose(); 63 clientManager.Dispose(); 64 return res; 65 } 66 /// <summary> 67 /// 设置单体 68 /// </summary> 69 /// <typeparam name="T">值类型</typeparam> 70 /// <param name="key">键值</param> 71 /// <param name="t">值</param> 72 /// <param name="timeSpan">保存时间</param> 73 /// <param name="dbId">库Id</param> 74 /// <returns></returns> 75 public static bool Set<T>(string key, T t, TimeSpan timeSpan, long dbId = 0) 76 { 77 var clientManager = GetClientManager(dbId); 78 IRedisClient redis = clientManager.GetClient(); 79 var res = redis.Set<T>(key, t, timeSpan); 80 clientManager.DisposeClient((RedisNativeClient)redis); 81 redis.Dispose(); 82 clientManager.Dispose(); 83 return res; 84 } 85 /// <summary> 86 /// 设置单体 87 /// </summary> 88 /// <typeparam name="T">值类型</typeparam> 89 /// <param name="key">键值</param> 90 /// <param name="t">值</param> 91 /// <param name="dateTime">过期时间</param> 92 /// <returns></returns> 93 public static bool Set<T>(string key, T t, DateTime dateTime, long dbId = 0) 94 { 95 var clientManager = GetClientManager(dbId); 96 IRedisClient redis = clientManager.GetClient(); 97 var res = redis.Set<T>(key, t, dateTime); 98 clientManager.DisposeClient((RedisNativeClient)redis); 99 redis.Dispose(); 100 clientManager.Dispose(); 101 return res; 102 } 103 104 /// <summary> 105 /// 获取单体 106 /// </summary> 107 /// <typeparam name="T">值类型</typeparam> 108 /// <param name="key">键值</param> 109 /// <returns></returns> 110 public static T Get<T>(string key, long dbId = 0) where T : class 111 { 112 var clientManager = GetClientManager(dbId); 113 IRedisClient redis = clientManager.GetClient(); 114 var res = redis.Get<T>(key); 115 clientManager.DisposeClient((RedisNativeClient)redis); 116 redis.Dispose(); 117 clientManager.Dispose(); 118 return res; 119 } 120 /// <summary> 121 /// 移除单体 122 /// </summary> 123 /// <param name="key">键值</param> 124 public static bool Remove(string key, long dbId = 0) 125 { 126 var clientManager = GetClientManager(dbId); 127 IRedisClient redis = clientManager.GetClient(); 128 var res = redis.Remove(key); 129 clientManager.DisposeClient((RedisNativeClient)redis); 130 redis.Dispose(); 131 clientManager.Dispose(); 132 return res; 133 } 134 /// <summary> 135 /// 清空所有缓存 136 /// </summary> 137 public static void RemoveAll(long dbId = 0) 138 { 139 var clientManager = GetClientManager(dbId); 140 IRedisClient redis = clientManager.GetClient(); 141 redis.FlushDb(); 142 clientManager.DisposeClient((RedisNativeClient)redis); 143 redis.Dispose(); 144 clientManager.Dispose(); 145 } 146 #endregion 147 148 #region -- List -- 149 /// <summary> 150 /// 添加列表 151 /// </summary> 152 /// <typeparam name="T">类型</typeparam> 153 /// <param name="key">键值</param> 154 /// <param name="t">值</param> 155 /// <param name="dbId">库</param> 156 public static void List_Add<T>(string key, T t, long dbId = 0) 157 { 158 using (IRedisClient redis = CreateManager(dbId).GetClient()) 159 { 160 var redisTypedClient = redis.As<T>(); 161 redisTypedClient.AddItemToList(redisTypedClient.Lists[key], t); 162 } 163 } 164 /// <summary> 165 /// 移除列表某个值 166 /// </summary> 167 /// <typeparam name="T">类型</typeparam> 168 /// <param name="key">键值</param> 169 /// <param name="t">值</param> 170 /// <param name="dbId">库</param> 171 /// <returns></returns> 172 public static bool List_Remove<T>(string key, T t, long dbId = 0) 173 { 174 using (IRedisClient redis = CreateManager(dbId).GetClient()) 175 { 176 var redisTypedClient = redis.As<T>(); 177 return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0; 178 } 179 } 180 /// <summary> 181 /// 移除列表所有值 182 /// </summary> 183 /// <typeparam name="T">类型</typeparam> 184 /// <param name="key">键值</param> 185 /// <param name="dbId">库Id</param> 186 public static void List_RemoveAll<T>(string key, long dbId = 0) 187 { 188 using (IRedisClient redis = CreateManager(dbId).GetClient()) 189 { 190 var redisTypedClient = redis.As<T>(); 191 redisTypedClient.Lists[key].RemoveAll(); 192 } 193 } 194 /// <summary> 195 /// 获取列表数据条数 196 /// </summary> 197 /// <param name="key"></param> 198 /// <param name="dbId"></param> 199 /// <returns></returns> 200 public static long List_Count(string key, long dbId = 0) 201 { 202 using (IRedisClient redis = CreateManager(dbId).GetClient()) 203 { 204 return redis.GetListCount(key); 205 } 206 } 207 /// <summary> 208 /// 获取指定条数列表数据 209 /// </summary> 210 /// <typeparam name="T">类型</typeparam> 211 /// <param name="key">键值</param> 212 /// <param name="start">开始编号</param> 213 /// <param name="count">条数</param> 214 /// <param name="dbId">库</param> 215 /// <returns></returns> 216 public static List<T> List_GetRange<T>(string key, int start, int count, long dbId = 0) 217 { 218 using (IRedisClient redis = CreateManager(dbId).GetClient()) 219 { 220 var c = redis.As<T>(); 221 return c.Lists[key].GetRange(start, start + count - 1); 222 } 223 } 224 /// <summary> 225 /// 获取列表所有数据 226 /// </summary> 227 /// <typeparam name="T">类型</typeparam> 228 /// <param name="key">键值</param> 229 /// <param name="dbId">库数据</param> 230 /// <returns></returns> 231 public static List<T> List_GetList<T>(string key, long dbId = 0) 232 { 233 using (IRedisClient redis = CreateManager(dbId).GetClient()) 234 { 235 var c = redis.As<T>(); 236 return c.Lists[key].GetRange(0, c.Lists[key].Count); 237 } 238 } 239 /// <summary> 240 /// 获取列表分页数据 241 /// </summary> 242 /// <typeparam name="T">类型</typeparam> 243 /// <param name="key">键值</param> 244 /// <param name="pageIndex">页码</param> 245 /// <param name="pageSize">每页条数</param> 246 /// <param name="dbId">库</param> 247 /// <returns></returns> 248 public static List<T> List_GetList<T>(string key, int pageIndex, int pageSize, long dbId = 0) 249 { 250 int start = pageSize * (pageIndex - 1); 251 return List_GetRange<T>(key, start, pageSize, dbId); 252 } 253 #endregion 254 255 #region -- Set -- 256 /// <summary> 257 /// 添加集合 258 /// </summary> 259 /// <typeparam name="T">类型</typeparam> 260 /// <param name="key">键值</param> 261 /// <param name="t">数值</param> 262 /// <param name="dbId">库</param> 263 public static void Set_Add<T>(string key, T t, long dbId = 0) 264 { 265 using (IRedisClient redis = CreateManager(dbId).GetClient()) 266 { 267 var redisTypedClient = redis.As<T>(); 268 redisTypedClient.Sets[key].Add(t); 269 } 270 } 271 /// <summary> 272 /// 集合是否包含指定数据 273 /// </summary> 274 /// <typeparam name="T">类型</typeparam> 275 /// <param name="key">键值</param> 276 /// <param name="t">数值</param> 277 /// <param name="dbId">库</param> 278 /// <returns></returns> 279 public static bool Set_Contains<T>(string key, T t, long dbId = 0) 280 { 281 using (IRedisClient redis = CreateManager(dbId).GetClient()) 282 { 283 var redisTypedClient = redis.As<T>(); 284 return redisTypedClient.Sets[key].Contains(t); 285 } 286 } 287 /// <summary> 288 /// 移除集合某个值 289 /// </summary> 290 /// <typeparam name="T">类型</typeparam> 291 /// <param name="key">键值</param> 292 /// <param name="t">数值</param> 293 /// <param name="dbId">库</param> 294 /// <returns></returns> 295 public static bool Set_Remove<T>(string key, T t, long dbId = 0) 296 { 297 using (IRedisClient redis = CreateManager(dbId).GetClient()) 298 { 299 var redisTypedClient = redis.As<T>(); 300 return redisTypedClient.Sets[key].Remove(t); 301 } 302 } 303 #endregion 304 305 #region -- Hash -- 306 /// <summary> 307 /// 判断某个数据是否已经被缓存 308 /// </summary> 309 /// <typeparam name="T">类型</typeparam> 310 /// <param name="key">hashID</param> 311 /// <param name="dataKey">键值</param> 312 /// <param name="dbId">库</param> 313 /// <returns></returns> 314 public static bool Hash_Exist<T>(string key, string dataKey, long dbId = 0) 315 { 316 using (IRedisClient redis = CreateManager(dbId).GetClient()) 317 { 318 return redis.HashContainsEntry(key, dataKey); 319 } 320 } 321 322 /// <summary> 323 /// 存储数据到hash表 324 /// </summary> 325 /// <typeparam name="T">类型</typeparam> 326 /// <param name="key">hashID</param> 327 /// <param name="dataKey">键值</param> 328 /// <param name="t">数值</param> 329 /// <param name="dbId">库</param> 330 /// <returns></returns> 331 public static bool Hash_Set<T>(string key, string dataKey, T t, long dbId = 0) 332 { 333 using (IRedisClient redis = CreateManager(dbId).GetClient()) 334 { 335 string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t); 336 return redis.SetEntryInHash(key, dataKey, value); 337 } 338 } 339 /// <summary> 340 /// 移除hash中的某值 341 /// </summary> 342 /// <param name="key">hashID</param> 343 /// <param name="dataKey">键值</param> 344 /// <param name="dbId">库</param> 345 /// <returns></returns> 346 public static bool Hash_Remove(string key, string dataKey, long dbId = 0) 347 { 348 using (IRedisClient redis = CreateManager(dbId).GetClient()) 349 { 350 return redis.RemoveEntryFromHash(key, dataKey); 351 } 352 } 353 /// <summary> 354 /// 移除整个hash 355 /// </summary> 356 /// <param name="key">hashID</param> 357 /// <param name="dbId">库</param> 358 /// <returns></returns> 359 public static bool Hash_Remove(string key, long dbId = 0) 360 { 361 using (IRedisClient redis = CreateManager(dbId).GetClient()) 362 { 363 return redis.Remove(key); 364 } 365 } 366 /// <summary> 367 /// 从hash表获取数据 368 /// </summary> 369 /// <typeparam name="T">类型</typeparam> 370 /// <param name="key">hashID</param> 371 /// <param name="dataKey">键值</param> 372 /// <param name="dbId">库</param> 373 /// <returns></returns> 374 public static T Hash_Get<T>(string key, string dataKey, long dbId = 0) 375 { 376 using (IRedisClient redis = CreateManager(dbId).GetClient()) 377 { 378 string value = redis.GetValueFromHash(key, dataKey); 379 return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(value); 380 } 381 } 382 /// <summary> 383 /// 获取整个hash的数据 384 /// </summary> 385 /// <typeparam name="T">类型</typeparam> 386 /// <param name="key">hashID</param> 387 /// <param name="dbId">库</param> 388 /// <returns></returns> 389 public static List<T> Hash_GetAll<T>(string key, long dbId = 0) 390 { 391 using (IRedisClient redis = CreateManager(dbId).GetClient()) 392 { 393 var list = redis.GetHashValues(key); 394 if (list != null && list.Count > 0) 395 { 396 List<T> result = new List<T>(); 397 foreach (var item in list) 398 { 399 var value = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item); 400 result.Add(value); 401 } 402 return result; 403 } 404 return null; 405 } 406 } 407 #endregion 408 409 #region -- SortedSet -- 410 /// <summary> 411 /// 添加数据到 SortedSet 412 /// </summary> 413 /// <typeparam name="T">类型</typeparam> 414 /// <param name="key">集合id</param> 415 /// <param name="t">数值</param> 416 /// <param name="score">排序码</param> 417 /// <param name="dbId">库</param> 418 public static bool SortedSet_Add<T>(string key, T t, double score, long dbId = 0) 419 { 420 using (IRedisClient redis = CreateManager(dbId).GetClient()) 421 { 422 string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t); 423 return redis.AddItemToSortedSet(key, value, score); 424 } 425 } 426 /// <summary> 427 /// 移除数据从SortedSet 428 /// </summary> 429 /// <typeparam name="T">类型</typeparam> 430 /// <param name="key">集合id</param> 431 /// <param name="t">数值</param> 432 /// <param name="dbId">库</param> 433 /// <returns></returns> 434 public static bool SortedSet_Remove<T>(string key, T t, long dbId = 0) 435 { 436 using (IRedisClient redis = CreateManager(dbId).GetClient()) 437 { 438 string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t); 439 return redis.RemoveItemFromSortedSet(key, value); 440 } 441 } 442 /// <summary> 443 /// 修剪SortedSet 444 /// </summary> 445 /// <param name="key">键值</param> 446 /// <param name="size">保留的条数</param> 447 /// <param name="dbId">库</param> 448 /// <returns></returns> 449 public static long SortedSet_Trim(string key, int size, long dbId = 0) 450 { 451 using (IRedisClient redis = CreateManager(dbId).GetClient()) 452 { 453 return redis.RemoveRangeFromSortedSet(key, size, 9999999); 454 } 455 } 456 /// <summary> 457 /// 获取SortedSet的长度 458 /// </summary> 459 /// <param name="key">键值</param> 460 /// <param name="dbId">库</param> 461 /// <returns></returns> 462 public static long SortedSet_Count(string key, long dbId = 0) 463 { 464 using (IRedisClient redis = CreateManager(dbId).GetClient()) 465 { 466 return redis.GetSortedSetCount(key); 467 } 468 } 469 470 /// <summary> 471 /// 获取SortedSet的分页数据 472 /// </summary> 473 /// <typeparam name="T">类型</typeparam> 474 /// <param name="key">键值</param> 475 /// <param name="pageIndex">页码</param> 476 /// <param name="pageSize">每页条数</param> 477 /// <param name="dbId">库</param> 478 /// <returns></returns> 479 public static List<T> SortedSet_GetList<T>(string key, int pageIndex, int pageSize, long dbId = 0) 480 { 481 using (IRedisClient redis = CreateManager(dbId).GetClient()) 482 { 483 var list = redis.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1); 484 if (list != null && list.Count > 0) 485 { 486 List<T> result = new List<T>(); 487 foreach (var item in list) 488 { 489 var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item); 490 result.Add(data); 491 } 492 return result; 493 } 494 } 495 return null; 496 } 497 498 499 /// <summary> 500 /// 获取SortedSet的全部数据 501 /// </summary> 502 /// <typeparam name="T">类</typeparam> 503 /// <param name="key">键值</param> 504 /// <param name="dbId">库</param> 505 /// <returns></returns> 506 public static List<T> SortedSet_GetListALL<T>(string key, long dbId = 0) 507 { 508 using (IRedisClient redis = CreateManager(dbId).GetClient()) 509 { 510 var list = redis.GetRangeFromSortedSet(key, 0, 9999999); 511 if (list != null && list.Count > 0) 512 { 513 List<T> result = new List<T>(); 514 foreach (var item in list) 515 { 516 var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item); 517 result.Add(data); 518 } 519 return result; 520 } 521 } 522 return null; 523 } 524 #endregion 525 526 #region 公用方法 527 /// <summary> 528 /// 设置缓存过期 529 /// </summary> 530 /// <param name="key">键值</param> 531 /// <param name="datetime">过期时间</param> 532 /// <param name="dbId">库</param> 533 public static void SetExpire(string key, DateTime datetime, long dbId = 0) 534 { 535 using (IRedisClient redis = CreateManager(dbId).GetClient()) 536 { 537 redis.ExpireEntryAt(key, datetime); 538 } 539 } 540 #endregion 541 }