终端一体化运控平台
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

70 satır
2.2 KiB

  1. using ServiceStack.Redis;
  2. using System.Diagnostics;
  3. namespace Communication
  4. {
  5. public class RedisHelper
  6. {
  7. private volatile static RedisHelper _Instance;
  8. public static RedisHelper GetInstance => _Instance ?? (_Instance = new RedisHelper());
  9. private RedisHelper() { }
  10. RedisClient client;
  11. public async Task<bool> ConnectAsync()
  12. {
  13. return await Task.Factory.StartNew(new Func<bool>(() =>
  14. {
  15. if (client == null)
  16. {
  17. BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog("开始连接 Redis");
  18. client = new RedisClient("124.222.238.75", 16000, "123456", 1);
  19. client.ConnectTimeout = 5000;
  20. Stopwatch sw = new Stopwatch();
  21. sw.Start();
  22. while (!client.IsSocketConnected())
  23. {
  24. if (sw.ElapsedMilliseconds >= client.ConnectTimeout) break;
  25. Thread.Sleep(1000);
  26. }
  27. string status = client.IsSocketConnected() ? "成功" : "失败";
  28. BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog($"Redis 连接{status}");
  29. }
  30. return client.IsSocketConnected();
  31. }));
  32. }
  33. /// <summary>
  34. /// 清除所有redis 数据
  35. /// </summary>
  36. public void FlushDb()
  37. {
  38. client?.FlushDb();
  39. }
  40. /// <summary>
  41. /// 设置值
  42. /// </summary>
  43. /// <typeparam name="TValue"></typeparam>
  44. /// <param name="key"></param>
  45. /// <param name="value"></param>
  46. public void SetValue<TValue>(string key, TValue value)
  47. {
  48. var res = client?.Set<TValue>(key, value);
  49. }
  50. /// <summary>
  51. /// 获取值
  52. /// </summary>
  53. /// <typeparam name="TResult"></typeparam>
  54. /// <param name="key"></param>
  55. /// <returns></returns>
  56. public TResult GetValue<TResult>(string key)
  57. {
  58. if (client == null) return default(TResult);
  59. return client.Get<TResult>(key);
  60. }
  61. }
  62. }