C#封装StackExchange.Redis操作
1 using System; 2 using StackExchange.Redis; 3 using System.Collections.Generic; 4 using System.Linq; 5 using Newtonsoft.Json; 6 7 namespace Tools 8 { 9 public class RedisHelper 10 { 11 #region 12 //执行顺序---静态字段---静态构造函数---构造函数 13 private static ConnectionMultiplexer redis; 14 15 static RedisHelper() 16 { 17 if (redis == null || redis.IsConnected) 18 { 19 redis = ConnectionMultiplexer.Connect("localhost, abortConnect=false"); 20 } 21 } 22 23 #endregion 24 25 #region redis 字符串(string)操作 26 27 /// <summary> 28 /// 设置指定键的值 29 /// </summary> 30 /// <param name="key"></param> 31 /// <param name="value"></param> 32 /// <returns></returns> 33 public static bool StringSet(string key, string value) 34 { 35 return redis.GetDatabase().StringSet(key, value); 36 } 37 38 /// <summary> 39 /// 获取指定键的值 40 /// </summary> 41 /// <param name="key"></param> 42 /// <returns></returns> 43 public static object StringGet(string key) 44 { 45 return redis.GetDatabase().StringGet(key); 46 } 47 48 /// <summary> 49 /// 获取存储在键上的字符串的子字符串 50 /// </summary> 51 /// <param name="key"></param> 52 /// <param name="start"></param> 53 /// <param name="end"></param> 54 /// <returns></returns> 55 public static object StringGet(string key, int start, int end) 56 { 57 return redis.GetDatabase().StringGetRange(key, start, end); 58 } 59 60 /// <summary> 61 /// 设置键的字符串值并返回其旧值 62 /// </summary> 63 /// <param name="key"></param> 64 /// <param name="value"></param> 65 /// <returns></returns> 66 public static object StringGetAndSet(string key, string value) 67 { 68 return redis.GetDatabase().StringGetSet(key, value); 69 } 70 71 /// <summary> 72 /// 返回在键处存储的字符串值中偏移处的位值 73 /// </summary> 74 /// <param name="key"></param> 75 /// <param name="offset"></param> 76 /// <returns></returns> 77 public static bool StringGetBit(string key, long offset) 78 { 79 return redis.GetDatabase().StringGetBit(key, offset); 80 } 81 82 /// <summary> 83 /// 获取所有给定键的值 84 /// </summary> 85 /// <param name="keys"></param> 86 /// <returns></returns> 87 public static List<object> StringMultiGet(string[] keys) 88 { 89 List<object> list = new List<object>(); 90 for (int i = 0; i < keys.Length; i++) 91 { 92 list.Add(redis.GetDatabase().StringGet(keys[i])); 93 } 94 return list; 95 } 96 97 /// <summary> 98 /// 存储在键上的字符串值中设置或清除偏移处的位 99 /// </summary> 100 /// <param name="key"></param> 101 /// <param name="offset"></param> 102 /// <param name="value"></param> 103 /// <returns></returns> 104 public static bool StringSetBit(string key, long offset) 105 { 106 return redis.GetDatabase().StringSetBit(key, offset, true); 107 } 108 109 /// <summary> 110 /// 使用键和到期时间来设置值 111 /// </summary> 112 /// <param name="key"></param> 113 /// <param name="value"></param> 114 /// <param name="expiry"></param> 115 /// <returns></returns> 116 public static bool StringSet(string key, string value, TimeSpan expiry) 117 { 118 return redis.GetDatabase().StringSet(key, value, expiry); 119 } 120 121 /// <summary> 122 /// 设置键的值,仅当键不存在时 123 /// </summary> 124 /// <param name="key"></param> 125 /// <param name="value"></param> 126 /// <returns></returns> 127 public static void StringSetIfAbsent(string key, string value) 128 { 129 if (redis.GetDatabase().StringGet(key) == RedisValue.Null) 130 { 131 redis.GetDatabase().StringSet(key, value); 132 } 133 } 134 135 /// <summary> 136 /// 在指定偏移处开始的键处覆盖字符串的一部分 137 /// </summary> 138 /// <param name="key">键值</param> 139 /// <param name="value">值</param> 140 /// <param name="offset">偏移量</param> 141 /// <returns></returns> 142 public static object StringSet(string key, long offset, string value) 143 { 144 return redis.GetDatabase().StringSetRange(key, offset, value); 145 } 146 147 /// <summary> 148 /// 获取存储在键中的值的长度 149 /// </summary> 150 /// <param name="key">键值</param> 151 /// <returns></returns> 152 public static long StringSize(string key) 153 { 154 return redis.GetDatabase().StringLength(key); 155 } 156 157 /// <summary> 158 /// 为多个键分别设置它们的值 159 /// </summary> 160 /// <param name="keys"></param> 161 /// <returns></returns> 162 public static void StringMultiSet(Dictionary<string, string> dic) 163 { 164 foreach (KeyValuePair<string, string> key in dic) 165 { 166 redis.GetDatabase().StringSet(key.Key, key.Value); 167 } 168 } 169 170 /// <summary> 171 /// 为多个键分别设置它们的值,仅当键不存在时 172 /// </summary> 173 /// <param name="keys">键值集合</param> 174 /// <returns></returns> 175 public static void StringMultiSetIfAbsent(Dictionary<string, string> dic) 176 { 177 foreach (KeyValuePair<string, string> key in dic) 178 { 179 //判断键值是否存在 180 if (redis.GetDatabase().StringGet(key.Key) == RedisValue.Null) 181 { 182 redis.GetDatabase().StringSet(key.Key, key.Value); 183 } 184 } 185 } 186 187 /// <summary> 188 /// 将键的整数值按给定的数值增加 189 /// </summary> 190 /// <param name="key">键值</param> 191 /// <param name="value">给定的数值</param> 192 /// <returns></returns> 193 public static double StringIncrement(string key, double value) 194 { 195 return redis.GetDatabase().StringIncrement(key, value); 196 } 197 198 /// <summary> 199 /// 在key键对应值的右面追加值value 200 /// </summary> 201 /// <param name="key"></param> 202 /// <param name="value"></param> 203 /// <returns></returns> 204 public static long StringAppend(string key, string value) 205 { 206 return redis.GetDatabase().StringAppend(key, value); 207 } 208 209 /// <summary> 210 /// 删除某个键值 211 /// </summary> 212 /// <param name="key"></param> 213 /// <returns></returns> 214 public static bool StringDelete(string key) 215 { 216 return false; 217 } 218 219 #endregion 220 221 #region redis 哈希/散列/字典(Hash)操作 222 223 /// <summary> 224 /// 删除指定的哈希字段 225 /// </summary> 226 /// <param name="key"></param> 227 /// <param name="field"></param> 228 /// <returns></returns> 229 public static bool HashDelete(string key, string field) 230 { 231 return redis.GetDatabase().HashDelete(key, field); 232 } 233 234 /// <summary> 235 /// 判断是否存在散列字段 236 /// </summary> 237 /// <param name=""></param> 238 /// <param name=""></param> 239 /// <returns></returns> 240 public static bool HashHasKey(string key, string field) 241 { 242 return redis.GetDatabase().HashExists(key, field); 243 } 244 245 /// <summary> 246 /// 获取存储在指定键的哈希字段的值 247 /// </summary> 248 /// <param name="key"></param> 249 /// <param name="field"></param> 250 /// <returns></returns> 251 public static object HashGet(string key, string field) 252 { 253 return redis.GetDatabase().HashGet(key, field); 254 } 255 256 /// <summary> 257 /// 获取存储在指定键的哈希中的所有字段和值 258 /// </summary> 259 /// <param name="key"></param> 260 /// <returns></returns> 261 public static Dictionary<string, object> HashGetAll(string key) 262 { 263 Dictionary<string, object> dic = new Dictionary<string, object>(); 264 var collection = redis.GetDatabase().HashGetAll(key); 265 foreach (var item in collection) 266 { 267 dic.Add(item.Name, item.Value); 268 } 269 return dic; 270 } 271 272 /// <summary> 273 /// 将哈希字段的浮点值按给定数值增加 274 /// </summary> 275 /// <param name="key"></param> 276 /// <param name="field"></param> 277 /// <param name="value">给定的数值</param> 278 /// <returns></returns> 279 public static double HashIncrement(string key, string field, double value) 280 { 281 return redis.GetDatabase().HashIncrement(key, field, value); 282 } 283 284 /// <summary> 285 /// 获取哈希中的所有字段 286 /// </summary> 287 /// <param name="key"></param> 288 /// <returns></returns> 289 public static string[] HashKeys(string key) 290 { 291 return redis.GetDatabase().HashKeys(key).ToStringArray(); 292 } 293 294 /// <summary> 295 /// 获取散列中的字段数量 296 /// </summary> 297 /// <param name="key"></param> 298 /// <returns></returns> 299 public static long HashSize(string key) 300 { 301 return redis.GetDatabase().HashLength(key); 302 } 303 304 /// <summary> 305 /// 获取所有给定哈希字段的值 306 /// </summary> 307 /// <param name="key"></param> 308 /// <param name="hashKeys"></param> 309 /// <returns></returns> 310 public static List<object> HashMultiGet(string key, List<string> hashKeys) 311 { 312 List<object> result = new List<object>(); 313 foreach (string field in hashKeys) 314 { 315 result.Add(redis.GetDatabase().HashGet(key, field)); 316 } 317 return result; 318 } 319 320 /// <summary> 321 /// 为多个哈希字段分别设置它们的值 322 /// </summary> 323 /// <param name="key"></param> 324 /// <param name="dic"></param> 325 /// <returns></returns> 326 public static void HashPutAll(string key, Dictionary<string, string> dic) 327 { 328 List<HashEntry> list = new List<HashEntry>(); 329 for (int i = 0; i < dic.Count; i++) 330 { 331 KeyValuePair<string, string> param = dic.ElementAt(i); 332 list.Add(new HashEntry(param.Key, param.Value)); 333 } 334 redis.GetDatabase().HashSet(key, list.ToArray()); 335 } 336 337 /// <summary> 338 /// 设置散列字段的字符串值 339 /// </summary> 340 /// <param name="key"></param> 341 /// <param name="field"></param> 342 /// <param name="value"></param> 343 /// <returns></returns> 344 public static void HashPut(string key, string field, string value) 345 { 346 redis.GetDatabase().HashSet(key, new HashEntry[] { new HashEntry(field, value) }); 347 } 348 349 /// <summary> 350 /// 仅当字段不存在时,才设置散列字段的值 351 /// </summary> 352 /// <param name="key"></param> 353 /// <param name="fiels"></param> 354 /// <param name="value"></param> 355 /// <returns></returns> 356 public static void HashPutIfAbsent(string key, string field, string value) 357 { 358 if (!HashHasKey(key, field)) 359 { 360 redis.GetDatabase().HashSet(key, new HashEntry[] { new HashEntry(field, value) }); 361 } 362 } 363 364 /// <summary> 365 /// 获取哈希中的所有值 366 /// </summary> 367 /// <param name="key"></param> 368 /// <returns></returns> 369 public static string[] HashValues(string key) 370 { 371 return redis.GetDatabase().HashValues(key).ToStringArray(); 372 } 373 374 /// <summary> 375 /// redis中获取指定键的值并返回对象 376 /// </summary> 377 /// <typeparam name="T"></typeparam> 378 /// <param name="key"></param> 379 /// <returns></returns> 380 public static T GetHashValue<T>(string key) 381 { 382 HashEntry[] array = redis.GetDatabase().HashGetAll(key); 383 Dictionary<string, object> dic = new Dictionary<string, object>(); 384 for (int i = 0; i < array.Length; i++) 385 { 386 dic.Add(array[i].Name, array[i].Value); 387 } 388 string strJson = JsonConvert.SerializeObject(dic); 389 return JsonConvert.DeserializeObject<T>(strJson); 390 } 391 392 /// <summary> 393 /// 把指定对象存储在键值为key的redis中 394 /// </summary> 395 /// <typeparam name="T"></typeparam> 396 /// <param name="t"></param> 397 /// <param name="key"></param> 398 public static void SetHashValue<T>(T t, string key) 399 { 400 string strJson = JsonConvert.SerializeObject(t); 401 Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(strJson); 402 HashPutAll(key, param); 403 } 404 405 #endregion 406 407 #region redis 列表(List)操作 408 409 /// <summary> 410 /// 从左向右存压栈 411 /// </summary> 412 /// <param name="key"></param> 413 /// <param name="value"></param> 414 /// <returns></returns> 415 public static long ListLeftPush(string key, string value) 416 { 417 return redis.GetDatabase().ListLeftPush(key, value); 418 } 419 420 /// <summary> 421 /// 从左出栈 422 /// </summary> 423 /// <param name="key"></param> 424 /// <returns></returns> 425 public static object ListLeftPop(string key) 426 { 427 return redis.GetDatabase().ListLeftPop(key); 428 } 429 430 /// <summary> 431 /// 队/栈长 432 /// </summary> 433 /// <param name="key"></param> 434 /// <returns></returns> 435 public static long ListSize(string key) 436 { 437 return redis.GetDatabase().ListLength(key); 438 } 439 440 /// <summary> 441 /// 范围检索,返回List 442 /// </summary> 443 /// <param name="key"></param> 444 /// <param name="start"></param> 445 /// <param name="end"></param> 446 /// <returns></returns> 447 public static string[] ListRange(string key, int start, int end) 448 { 449 return redis.GetDatabase().ListRange(key, start, end).ToStringArray(); 450 } 451 452 /// <summary> 453 /// 移除key中值为value的i个,返回删除的个数;如果没有这个元素则返回0 454 /// </summary> 455 /// <param name="key"></param> 456 /// <param name="i"></param> 457 /// <param name="value"></param> 458 /// <returns></returns> 459 public static long ListRemove(string key, string value) 460 { 461 return redis.GetDatabase().ListRemove(key, value); 462 } 463 464 /// <summary> 465 /// 检索 466 /// </summary> 467 /// <param name="key"></param> 468 /// <param name="index"></param> 469 /// <returns></returns> 470 public static object ListIndex(string key, long index) 471 { 472 return redis.GetDatabase().ListGetByIndex(key, index); 473 } 474 475 /// <summary> 476 /// 赋值 477 /// </summary> 478 /// <param name="key"></param> 479 /// <param name="index"></param> 480 /// <param name="value"></param> 481 /// <returns></returns> 482 public static void ListSet(string key, int index, string value) 483 { 484 redis.GetDatabase().ListSetByIndex(key, index, value); 485 } 486 487 /// <summary> 488 /// 裁剪,删除除了[start,end]以外的所有元素 489 /// </summary> 490 /// <param name="key"></param> 491 /// <param name="start"></param> 492 /// <param name="end"></param> 493 /// <returns></returns> 494 public static void ListTrim(string key, int start, int end) 495 { 496 redis.GetDatabase().ListTrim(key, start, end); 497 } 498 499 /// <summary> 500 /// 将源key的队列的右边的一个值删除,然后塞入目标key的队列的左边,返回这个值 501 /// </summary> 502 /// <param name="sourceKey"></param> 503 /// <param name="destinationKey"></param> 504 /// <returns></returns> 505 public static object ListRightPopAndLeftPush(string sourceKey, string destinationKey) 506 { 507 return redis.GetDatabase().ListRightPopLeftPush(sourceKey, destinationKey); 508 } 509 510 #endregion 511 512 #region redis 集合(Set)操作 513 514 /// <summary> 515 /// 集合添加元素 516 /// </summary> 517 /// <param name="key"></param> 518 /// <param name="value"></param> 519 public static void SetAdd(string key, string value) 520 { 521 redis.GetDatabase().SetAdd(key, value); 522 } 523 524 /// <summary> 525 /// 集合组合操作 526 /// </summary> 527 /// <param name="point">操作标示:0--并集;1--交集;2--差集</param> 528 /// <param name="firstKey">第一个集合的键值</param> 529 /// <param name="secondKey">第二个集合的键值</param> 530 public static string[] SetCombine(int point, string firstKey, string secondKey) 531 { 532 RedisValue[] array; 533 switch (point) 534 { 535 case 0: 536 array = redis.GetDatabase().SetCombine(SetOperation.Union, firstKey, secondKey); 537 break; 538 case 1: 539 array = redis.GetDatabase().SetCombine(SetOperation.Intersect, firstKey, secondKey); 540 break; 541 case 2: 542 array = redis.GetDatabase().SetCombine(SetOperation.Difference, firstKey, secondKey); 543 break; 544 default: 545 array = new RedisValue[0]; 546 break; 547 } 548 return array.ToStringArray(); 549 } 550 551 /// <summary> 552 /// 553 /// </summary> 554 /// <param name="key"></param> 555 /// <param name="value"></param> 556 /// <returns></returns> 557 public static bool SetContains(string key, string value) 558 { 559 return redis.GetDatabase().SetContains(key, value); 560 } 561 562 /// <summary> 563 /// 返回对应键值集合的长度 564 /// </summary> 565 /// <param name="key"></param> 566 /// <returns></returns> 567 public static long SetLength(string key) 568 { 569 return redis.GetDatabase().SetLength(key); 570 } 571 572 /// <summary> 573 /// 根据键值返回集合中所有的value 574 /// </summary> 575 /// <param name="key"></param> 576 /// <returns></returns> 577 public static string[] SetMembers(string key) 578 { 579 return redis.GetDatabase().SetMembers(key).ToStringArray(); 580 } 581 582 /// <summary> 583 /// 将成员从源集移动到目标集 584 /// </summary> 585 /// <param name="sourceKey">源集key</param> 586 /// <param name="destinationKey">目标集key</param> 587 /// <param name="value"></param> 588 public static bool SetMove(string sourceKey, string destinationKey, string value) 589 { 590 return redis.GetDatabase().SetMove(sourceKey, destinationKey, value); 591 } 592 593 /// <summary> 594 /// 移除集合中指定键值随机元素 595 /// </summary> 596 /// <param name="key"></param> 597 public static string SetPop(string key) 598 { 599 return redis.GetDatabase().SetPop(key); 600 } 601 602 /// <summary> 603 /// 返回集合中指定键值随机元素 604 /// </summary> 605 /// <param name="key"></param> 606 /// <returns></returns> 607 public static string SetRandomMember(string key) 608 { 609 return redis.GetDatabase().SetRandomMember(key); 610 } 611 612 /// <summary> 613 /// 614 /// </summary> 615 /// <param name="key"></param> 616 /// <param name="count"></param> 617 public static string[] SetRandomMembers(string key, long count) 618 { 619 return redis.GetDatabase().SetRandomMembers(key, count).ToStringArray(); 620 } 621 622 /// <summary> 623 /// 移除集合中指定key值和value 624 /// </summary> 625 /// <param name="key"></param> 626 /// <param name="value"></param> 627 public static void SetRemove(string key, string value) 628 { 629 redis.GetDatabase().SetRemove(key, value); 630 } 631 632 /// <summary> 633 /// 634 /// </summary> 635 /// <param name="key"></param> 636 public static void SetScan(string key) 637 { 638 redis.GetDatabase().SetScan(key); 639 } 640 641 #endregion 642 643 #region redis 有序集合(sorted set)操作 644 645 public static void Method(string key, string value, double score) 646 { 647 redis.GetDatabase().SortedSetAdd(key, new SortedSetEntry[] { new SortedSetEntry(value, score) }); 648 } 649 650 #endregion 651 } 652 }
上面用的是.NetStandard类库
再来一个Protobuf进行的封装
1 using System; 2 using System.IO; 3 using ProtoBuf; 4 5 namespace Tools 6 { 7 /// <summary> 8 /// ProtobufHelper类 9 /// </summary> 10 public class ProtobufHelper 11 { 12 /* 使用Protobuf的类需要添加ProtoContract特性 13 * 使用Protobuf的类的字段需要添加ProtoMember(序号)特性 14 * 15 */ 16 /// <summary> 17 /// 对象序列化为字节 18 /// </summary> 19 /// <typeparam name="T"></typeparam> 20 /// <param name="instance"></param> 21 /// <returns></returns> 22 public static byte[] ObjectToBytes<T>(T instance) 23 { 24 try 25 { 26 byte[] array; 27 if (instance == null) 28 { 29 array = new byte[0]; 30 } 31 else 32 { 33 using (MemoryStream ms = new MemoryStream()) 34 { 35 Serializer.Serialize<T>(ms, instance); 36 array = new byte[ms.Length]; 37 ms.Position = 0L; 38 ms.Read(array, 0, array.Length); 39 } 40 } 41 return array; 42 } 43 catch (Exception ex) 44 { 45 return new byte[0]; 46 } 47 } 48 49 /// <summary> 50 /// 字节反序列化为对象 51 /// </summary> 52 /// <typeparam name="T"></typeparam> 53 /// <param name="array"></param> 54 /// <param name="offset"></param> 55 /// <param name="length"></param> 56 /// <returns></returns> 57 public static T BytesToObject<T>(byte[] array, int offset, int length) 58 { 59 if (array == null) 60 { 61 return default(T); 62 } 63 try 64 { 65 T result; 66 using (MemoryStream ms = new MemoryStream()) 67 { 68 ms.Write(array, 0, array.Length); 69 ms.Position = 0L; 70 result = Serializer.Deserialize<T>(ms); 71 } 72 return result; 73 } 74 catch (Exception ex) 75 { 76 return default(T); 77 } 78 } 79 } 80 }