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.

94 líneas
3.0KB

  1. using HealthMonitor.Core.Dal;
  2. using HealthMonitor.Core.Query;
  3. using HealthMonitor.Core.Query.Extensions;
  4. using HealthMonitor.Util.Entities.HealthMonitor;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Logging;
  7. using Newtonsoft.Json;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. namespace HealthMonitor.Service.Cache
  11. {
  12. public class BloodPressReferenceValueCacheManager
  13. {
  14. private readonly ILogger<BloodPressReferenceValueCacheManager> _logger;
  15. protected readonly IHealthMonitorDataAccessor _dataAccessor;
  16. private static object _syncLocker = new object();
  17. private MD5 _md5;
  18. private const string CACHE_KEY_BP_REF_VALUE = "HM_REF_Val_";
  19. public BloodPressReferenceValueCacheManager(
  20. IHealthMonitorDataAccessor dataAccessor,
  21. ILogger<BloodPressReferenceValueCacheManager> logger
  22. )
  23. {
  24. _md5 = MD5.Create();
  25. _dataAccessor = dataAccessor;
  26. _logger = logger;
  27. }
  28. public async Task<HmBloodPressReferenceValue> GetBloodPressReferenceValueAsync(int age, int gender,bool isHypertension)
  29. {
  30. var hashModel = new
  31. {
  32. Index = $"{age}-{gender}-{isHypertension}"
  33. };
  34. var hash = ComputeHash(hashModel);
  35. var cacheKey = CACHE_KEY_BP_REF_VALUE + $"{hash}";
  36. var bpRef = await RedisHelper.GetAsync<HmBloodPressReferenceValue>(cacheKey).ConfigureAwait(false);
  37. if (bpRef == null)
  38. {
  39. try
  40. {
  41. //bpRef = _dataAccessor
  42. //.GetFirstOrDefault<HmBloodPressReferenceValue>(
  43. //i =>
  44. //i.Age.Equals(age) &&
  45. //i.Gender.Equals(gender) &&
  46. //i.Hypertension.Equals(isHypertension)
  47. //);
  48. bpRef = await _dataAccessor
  49. .GetFirstOrDefaultAsync<HmBloodPressReferenceValue>
  50. (
  51. i =>
  52. i.Age.Equals(age) &&
  53. i.Gender.Equals(gender) &&
  54. i.Hypertension.Equals(isHypertension)
  55. );
  56. await RedisHelper.SetAsync(cacheKey, JsonConvert.SerializeObject(bpRef));
  57. return bpRef;
  58. }
  59. catch (Exception ex)
  60. {
  61. Console.WriteLine(ex.ToString() );
  62. return new HmBloodPressReferenceValue
  63. {
  64. Age = 0,
  65. };
  66. }
  67. }
  68. return bpRef;
  69. }
  70. private string ComputeHash(object data)
  71. {
  72. lock (_syncLocker)
  73. {
  74. var value = JsonConvert.SerializeObject(data);
  75. value = Convert.ToBase64String(_md5.ComputeHash(Encoding.UTF8.GetBytes(value)));
  76. return value;
  77. }
  78. }
  79. }
  80. }