RedisCls.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using ServiceStack.Redis;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace CarLocalMeter
  8. {
  9. public class RedisCls
  10. {
  11. public static RedisClient client = new RedisClient(AppConfigCache.redisIp, AppConfigCache.redisPort);//如果有密码则带密码,如果数据存在在db0外的比如db1则第四位为1
  12. Log lg = Log.GetInstance();
  13. public static List<string> getValue(out bool flag)
  14. {
  15. try
  16. {
  17. flag = true;
  18. return client.GetAllKeys();
  19. }
  20. catch
  21. {
  22. flag = false;
  23. return new List<string>();
  24. }
  25. }
  26. /// <summary>
  27. /// 获取redis数据
  28. /// </summary>
  29. /// <param name="key"></param>
  30. /// <returns></returns>
  31. public static T getValue<T>(string key, out bool flag)
  32. {
  33. try
  34. {
  35. flag = true;
  36. return client.Get<T>(key);
  37. }
  38. catch
  39. {
  40. flag = false;
  41. return default(T);
  42. }
  43. }
  44. /// <summary>
  45. /// 添加redis数据
  46. /// </summary>
  47. /// <param name="key"></param>
  48. /// <param name="value">可以是Json的字符串,也可以是List集合等</param>
  49. public static void setVaule<T>(string key, T value, out bool flag, DateTime dt = default)
  50. {
  51. try
  52. {
  53. flag = true;
  54. if (dt != null && dt > DateTime.Now)
  55. {
  56. client.Set<T>(key, value, dt);
  57. //client.ExpireEntryAt(key, DateTime.Now.AddSeconds(60));
  58. //client.ExpireEntryIn(key, TimeSpan.FromSeconds(20));
  59. }
  60. else
  61. client.Set<T>(key, value);
  62. }
  63. catch
  64. {
  65. flag = false;
  66. }
  67. }
  68. public static void setItemVaule(string key, string value, out bool flag, DateTime dt = default)
  69. {
  70. try
  71. {
  72. flag = true;
  73. if (dt != null && dt > DateTime.Now)
  74. {
  75. client.AddItemToSet(key, value);
  76. client.ExpireEntryAt(key, dt);
  77. //client.ExpireEntryIn(key, TimeSpan.FromSeconds(20));
  78. }
  79. else
  80. client.AddItemToSet(key, value);
  81. }
  82. catch
  83. {
  84. flag = false;
  85. }
  86. }
  87. public static void remoeItemValue(string key, string item, out bool flag)
  88. {
  89. try
  90. {
  91. flag = true;
  92. client.RemoveItemFromSet(key, item);
  93. }
  94. catch
  95. {
  96. flag = false;
  97. }
  98. }
  99. }
  100. }