No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

211 líneas
7.9KB

  1. using GpsCardGatewayPosition.Model.Config;
  2. using Microsoft.Extensions.Logging;
  3. using Microsoft.Extensions.Options;
  4. using Newtonsoft.Json.Linq;
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using TelpoDataService.Util;
  12. using TelpoDataService.Util.Entities.GpsCard;
  13. using TelpoDataService.Util.QueryObjects;
  14. using TelpoDataService.Util.Models;
  15. using TelpoDataService.Util.Clients;
  16. using GpsCardGatewayPosition.Model.Cache;
  17. namespace GpsCardGatewayPosition.Service.Cache
  18. {
  19. public class DeviceCacheManager
  20. {
  21. private const string CACHE_KEY_DEVICE = "Device_";
  22. private const string CACHE_KEY_DEVICESTATUS = "DeviceStatus_";
  23. private const string CACHE_HASH_KEY_POSITIONSTATUS = "#DevicePositionHash";
  24. private const string CACHE_HASH_KEY_GPSDEVICEPERSON = "#GPSDEVICE_PERSON_HASH";
  25. private const string CACHE_HASH_DEVICESTATUS = "#DEVICE_STATUS_HASH";
  26. private const string CACHE_KEY_GPSDEVICE_WATCH_CONFIG = "#GPSDEVICE_WATCH_CONFIG_HASH";
  27. private readonly ServiceConfig _configService;
  28. private readonly GpsCardAccessorClient<GpsDevice> _deviceApiClient;
  29. private readonly GpsCardAccessorClient<GpsDeviceStatus> _deviceStatusApiClient;
  30. private readonly ILogger<DeviceCacheManager> _logger;
  31. private int DefaultDurationSeconds { get; }
  32. public DeviceCacheManager(IOptions<ServiceConfig> optConfigService, IOptions<AppsettingsConfig> optConfigAppsettings,
  33. GpsCardAccessorClient<GpsDevice> deviceApiClient, GpsCardAccessorClient<GpsDeviceStatus> deviceStatusApiClient,
  34. ILogger<DeviceCacheManager> logger)
  35. {
  36. _configService = optConfigService.Value;
  37. _deviceApiClient = deviceApiClient;
  38. _deviceStatusApiClient = deviceStatusApiClient;
  39. _logger = logger;
  40. DefaultDurationSeconds = optConfigAppsettings.Value.DefaultDurationSeconds;
  41. }
  42. public async Task<GpsDevice> GetDeviceBySerialNoAsync(string messageId, string sn)
  43. {
  44. string key = CACHE_KEY_DEVICE + sn;
  45. var device = await RedisHelper.GetAsync<GpsDevice>(key).ConfigureAwait(false);
  46. if (device == null)
  47. {
  48. try
  49. {
  50. string url = _configService.TelpoDataUrl;
  51. var param = new GeneralParam
  52. {
  53. Filters = new List<QueryFilterCondition>
  54. {
  55. new QueryFilterCondition
  56. {
  57. Key=nameof(GpsDevice.Serialno),
  58. Value=sn,
  59. ValueType=QueryValueTypeEnum.String,
  60. Operator=QueryOperatorEnum.Equal
  61. }
  62. }
  63. };
  64. device = await _deviceApiClient.GetFirstAsync(param, new RequestHeader { RequestId = messageId }).ConfigureAwait(false);
  65. if (device != null)
  66. {
  67. await RedisHelper.SetAsync(key, device, DefaultDurationSeconds);
  68. }
  69. }
  70. catch (Exception ex)
  71. {
  72. _logger.LogError($"获取查询设备并更新缓存发生异常:{ex.Message}, {ex.StackTrace}");
  73. }
  74. }
  75. if (device != null && device.Serialno != sn)
  76. {
  77. _logger.LogError($"缓存不匹配(serialno), src: {sn}, dst: {device.Serialno}");
  78. }
  79. return device;
  80. }
  81. public async Task<GpsDeviceStatus> GetDeviceStatusBySerialNoAsync(string messageId, string sn)
  82. {
  83. string key = CACHE_KEY_DEVICESTATUS + sn;
  84. var deviceStatus = await RedisHelper.GetAsync<GpsDeviceStatus>(key).ConfigureAwait(false);
  85. if (deviceStatus == null)
  86. {
  87. try
  88. {
  89. var url = _configService.TelpoDataUrl;
  90. var param = new GeneralParam
  91. {
  92. Filters = new List<QueryFilterCondition>
  93. {
  94. new QueryFilterCondition
  95. {
  96. Key=nameof(GpsDeviceStatus.Serialno),
  97. Value=sn,
  98. ValueType=QueryValueTypeEnum.String,
  99. Operator=QueryOperatorEnum.Equal
  100. }
  101. }
  102. };
  103. deviceStatus = await _deviceStatusApiClient.GetFirstAsync(param, new RequestHeader { RequestId = messageId }).ConfigureAwait(false);
  104. if (deviceStatus != null)
  105. {
  106. RedisHelper.SetAsync(key, deviceStatus, DefaultDurationSeconds);
  107. }
  108. }
  109. catch (Exception ex)
  110. {
  111. _logger.LogError($"获取设备状态缓存发生异常:{ex.Message}, {ex.StackTrace}");
  112. }
  113. }
  114. return deviceStatus;
  115. }
  116. public async Task<DevicePositionStatus> GetPositionStatusCacheAsync(string sn)
  117. {
  118. if (string.IsNullOrWhiteSpace(sn)) return null;
  119. var status = await RedisHelper.HGetAsync<DevicePositionStatus>(CACHE_HASH_KEY_POSITIONSTATUS, sn);
  120. return status;
  121. }
  122. public void SetPositionStatusCache(string sn, DevicePositionStatus status)
  123. {
  124. if (string.IsNullOrWhiteSpace(sn) || status == null) return;
  125. RedisHelper.HSetAsync(CACHE_HASH_KEY_POSITIONSTATUS, sn, status);
  126. }
  127. public void SetDevice(GpsDevice device)
  128. {
  129. if (device == null) return;
  130. string key = CACHE_KEY_DEVICE + device.Serialno;
  131. RedisHelper.SetAsync(key, device, DefaultDurationSeconds);
  132. }
  133. public void SetDeviceStatus(GpsDeviceStatus deviceStatus)
  134. {
  135. if (deviceStatus == null) return;
  136. string key = CACHE_KEY_DEVICESTATUS + deviceStatus.Serialno;
  137. RedisHelper.SetAsync(key, deviceStatus, DefaultDurationSeconds);
  138. }
  139. /// <summary>
  140. /// 储存rssi 0或1 时的状态值
  141. /// </summary>
  142. /// <param name="deviceStatus"></param>
  143. public async Task SetStatusHashAsync(GpsDeviceStatus deviceStatus)
  144. {
  145. if (deviceStatus == null) return;
  146. string key = CACHE_KEY_DEVICESTATUS + deviceStatus.Serialno;
  147. await RedisHelper.SetAsync(key, deviceStatus, DefaultDurationSeconds);
  148. }
  149. public async Task<string> GetDeviceKeyBySerialNoAsync(string sn)
  150. {
  151. try
  152. {
  153. var hashKey = $"Telpol:HealthyDeviceKey:{sn}";
  154. var value = await RedisHelperDb0.HGetAsync<string>(hashKey, "data").ConfigureAwait(false);
  155. _logger.LogInformation($"{sn} 读取 Redis {hashKey}--{value}");
  156. return value ?? string.Empty;
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.LogError($"Redis发生异常:{ex.Message}, {ex.StackTrace}");
  161. return string.Empty;
  162. }
  163. }
  164. public async Task<JObject> GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(string sn)
  165. {
  166. if (string.IsNullOrWhiteSpace(sn)) return null;
  167. try
  168. {
  169. var config = await RedisHelperDb7.HGetAsync(CACHE_KEY_GPSDEVICE_WATCH_CONFIG, $"{sn}_0017").ConfigureAwait(false);
  170. return (JObject)JsonConvert.DeserializeObject(config);
  171. }
  172. catch (Exception ex)
  173. {
  174. _logger.LogWarning($"Redis DB7发生异常:{ex.Message}, {ex.StackTrace}");
  175. }
  176. return null;
  177. }
  178. }
  179. }