Files
BuYuHouDuan/FishGameSrc/FishGameService/GameService/FishSpawnConfigStore.cs
T
2026-10-12 16:22:04 +08:00

144 lines
4.3 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Text.Json;
using CommonDomain;
using CommonDomain.BaseModel;
using Microsoft.Extensions.Logging;
using RedisService;
namespace FishGameService.GameService
{
public class FishSpawnConfigStore
{
private readonly IRedisService _redisService;
private readonly ILogger<FishSpawnConfigStore> _logger;
private readonly ConcurrentDictionary<string, FishSpawnLevelConfig> _cache = new ConcurrentDictionary<string, FishSpawnLevelConfig>();
private FishSpawnConfigStoreModel _storeModel;
private DateTime _lastLoadTime = DateTime.MinValue;
private const int ReloadIntervalSeconds = 5;
public FishSpawnConfigStore(IRedisService redisService, ILogger<FishSpawnConfigStore> logger)
{
_redisService = redisService;
_logger = logger;
}
public FishSpawnLevelConfig GetOrLoad(int gameType, int roomLevel)
{
var cacheKey = $"{gameType}:{roomLevel}";
if (_cache.TryGetValue(cacheKey, out var levelConfig))
{
return levelConfig;
}
LoadFromRedis();
_cache.TryGetValue(cacheKey, out levelConfig);
if (levelConfig == null)
{
}
return levelConfig;
}
public void InvalidateAll()
{
_cache.Clear();
_storeModel = null;
_lastLoadTime = DateTime.MinValue;
}
private void AutoExtractAndSave()
{
try
{
var gameConfig = _redisService.GetGameConfig();
if (gameConfig != null)
{
var json = FishSpawnExtractor.ExtractToJson(gameConfig, _logger);
if (!string.IsNullOrWhiteSpace(json) && json != "{}")
{
_redisService.SetFishSpawnConfig(json);
return;
}
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[FishSpawnConfigStore] 从 GameConfig 提取出鱼配置失败");
}
}
private void LoadFromRedis()
{
if ((DateTime.Now - _lastLoadTime).TotalSeconds < ReloadIntervalSeconds && _storeModel != null)
{
return;
}
try
{
var json = _redisService.GetFishSpawnConfig();
if (string.IsNullOrWhiteSpace(json) || json == "{}")
{
AutoExtractAndSave();
json = _redisService.GetFishSpawnConfig();
if (string.IsNullOrWhiteSpace(json) || json == "{}")
{
return;
}
}
_storeModel = JsonSerializer.Deserialize<FishSpawnConfigStoreModel>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (_storeModel?.Levels == null || _storeModel.Levels.Count == 0)
{
return;
}
if (_storeModel.Levels.Keys.Any(k => !k.Contains(':')))
{
AutoExtractAndSave();
json = _redisService.GetFishSpawnConfig();
_storeModel = JsonSerializer.Deserialize<FishSpawnConfigStoreModel>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
_cache.Clear();
foreach (var kv in _storeModel.Levels)
{
if (kv.Key.Contains(':') && kv.Value != null)
{
_cache[kv.Key] = kv.Value;
}
}
_lastLoadTime = DateTime.Now;
}
catch (Exception ex)
{
_logger.LogError(ex, "[FishSpawnConfigStore] 从 Redis 加载出鱼配置失败");
}
}
}
}