using Dlhis.Middle.Apis; using Dlhis.Middle.Request; using Kurisu.AspNetCore.UnifyResultAndValidation; namespace Dlhis.Middle.Services.Implements; public class HealthCheckService : IHealthCheckService { private bool _isOffline; private readonly ILogger _logger; private readonly ISettingService _settingService; private readonly ICommonApi _healthCheckApi; private int _attempted; private bool _isBegin; public HealthCheckService(ILogger logger, ISettingService settingService, ICommonApi healthCheckApi) { _logger = logger; _settingService = settingService; _healthCheckApi = healthCheckApi; } public bool GetIsOffline() { return _isOffline; } public async Task DoHealthCheckAsync() { try { var factories = _settingService.GetFactories(); var response = await _healthCheckApi.CheckHealthAsync(new HealthCheckRequest { Factories = factories.ToList() }); if (response.Code == ApiStateCode.Success) { _attempted++; if (_attempted == 5) { _isOffline = false; _attempted = 0; } if (!_isBegin) { _isOffline = false; _isBegin = true; } await Task.Delay(_attempted * 1000); if (_isOffline == false) { _logger.LogInformation("Health"); return true; } } else { _isOffline = true; _logger.LogInformation("Error {message}", response.Msg); } } catch (Exception ex) { _logger.LogError("Failed cause :{reason}", ex.Message); _isOffline = true; await Task.Delay(5000); } return false; } }