| | |
| | | using Microsoft.Extensions.Logging; |
| | | using Newtonsoft.Json; |
| | | using WIDESEAWCS_Common; |
| | | using WIDESEAWCS_Core.Caches; |
| | | using WIDESEAWCS_Core.LogHelper; |
| | | using WIDESEAWCS_QuartzJob; |
| | | |
| | | namespace WIDESEAWCS_Tasks |
| | |
| | | private readonly ICacheService _cache; |
| | | |
| | | /// <summary> |
| | | /// 日志记录器 |
| | | /// </summary> |
| | | private readonly ILogger _logger; |
| | | |
| | | /// <summary> |
| | | /// 构造函数 |
| | | /// </summary> |
| | | /// <param name="cache">缓存服务实例(通常为 HybridCacheService)</param> |
| | | public RobotStateManager(ICacheService cache) |
| | | /// <param name="logger">日志记录器</param> |
| | | public RobotStateManager(ICacheService cache, ILogger logger) |
| | | { |
| | | _cache = cache; |
| | | _logger = logger; |
| | | } |
| | | |
| | | /// <summary> |
| | |
| | | newState.Version = DateTime.UtcNow.Ticks; |
| | | // 直接添加到缓存 |
| | | _cache.AddObject(cacheKey, newState); |
| | | _logger.LogDebug("TryUpdateStateSafely:创建新状态,IP: {IpAddress}", ipAddress); |
| | | QuartzLogger.Debug($"创建新状态,IP: {ipAddress}", ipAddress); |
| | | return true; |
| | | } |
| | | |
| | |
| | | newState.Version = DateTime.UtcNow.Ticks; |
| | | |
| | | // 尝试安全更新,如果版本冲突则返回 false |
| | | return _cache.TrySafeUpdate( |
| | | bool success = _cache.TrySafeUpdate( |
| | | cacheKey, |
| | | newState, |
| | | expectedVersion, |
| | | s => s.Version |
| | | ); |
| | | |
| | | if (!success) |
| | | { |
| | | _logger.LogWarning("TryUpdateStateSafely:版本冲突,更新失败,IP: {IpAddress},期望版本: {ExpectedVersion}", ipAddress, expectedVersion); |
| | | QuartzLogger.Warn($"版本冲突,更新失败,IP: {ipAddress}", ipAddress); |
| | | } |
| | | |
| | | return success; |
| | | } |
| | | |
| | | /// <summary> |