using IMCS.CCS.Common.Redis;
using IMCS.CCS.Entitys;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IMCS.CCS.Service.Impl
{
///
/// Job 运行 日志
///
public class JobLoggerService : IJobLoggerService
{
private ConcurrentBag jobLoggerInfos;
private string JobLoggerKey = "HC.Quartz:JobLogger";
private long ListMaxValue = 999999;//集合最大值
private readonly IDataStorageConfigurationService _dataStorageConfigurationService;
private readonly IRedisService _redisService;
public JobLoggerService(IDataStorageConfigurationService dataStorageConfigurationService, IRedisService redisService)
{
if (!dataStorageConfigurationService.IsUseRedis())
{
jobLoggerInfos ??= new ConcurrentBag();
}
_dataStorageConfigurationService = dataStorageConfigurationService;
_redisService = redisService;
}
private IEnumerable FindAll()
{
//if (_dataStorageConfigurationService.IsUseRedis())
//{
// var json = _redisService.Database.StringGet(JobLoggerKey);
// return string.IsNullOrWhiteSpace(json) ? new ConcurrentBag() : JsonConvert.DeserializeObject>(json);
//}
return jobLoggerInfos ?? new ConcurrentBag();
}
public IEnumerable FindListById(Guid tasksId)
{
if (tasksId == Guid.Empty) return new ConcurrentBag();
if (_dataStorageConfigurationService.IsUseRedis())
{
var json = _redisService.Database.StringGet($"{JobLoggerKey}:{tasksId}");
return string.IsNullOrWhiteSpace(json) ? new List() : JsonConvert.DeserializeObject>(json);
}
return FindAll().Where(w => w.TasksId == tasksId);
}
public void Write(JobLoggerInfo jobLoggerInfo)
{
if (jobLoggerInfo == null) return;
var tasksId = jobLoggerInfo?.TasksId ?? Guid.Empty;
if (_dataStorageConfigurationService.IsUseRedis())
{
var list = this.FindListById(tasksId)?.ToList() ?? new List();
if (list.Count > ListMaxValue)
{
list.Clear();
list ??= new List();
}
list.Add(jobLoggerInfo);
_redisService.Database.StringSet($"{JobLoggerKey}:{tasksId}", JsonConvert.SerializeObject(list));
}
else
{
jobLoggerInfos ??= new ConcurrentBag();
jobLoggerInfos.Add(jobLoggerInfo);
if (jobLoggerInfos.Count > ListMaxValue)
{
jobLoggerInfos.Clear();
jobLoggerInfos ??= new ConcurrentBag();
}
}
}
}
}