Files
zszq-trs/YLErpWeb/App/KafkaTask/ClientBalanceMonitorTotalKafkaTask.cs
T
2024-05-09 14:06:26 +08:00

87 lines
3.7 KiB
C#

using Newtonsoft.Json;
using YLErp.Abstract;
using YLErp.Modules.SwapModule;
namespace YLErp.Web.App.KafkaTask
{
/// <summary>
/// trs交易端客户资金监控
/// </summary>
public class ClientBalanceMonitorTotalKafkaTask : IHostedService, IDisposable
{
private readonly IYcLogger _logger;
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private string onRspClientMonitorConsumerTopic = string.Empty;
private string reqClientMonitorTopicGroupId = string.Empty;
private string reqClientMonitorTopic = string.Empty;
private KafkaConsumerHelper _kafkaConsumer;
private IKafkaProduce kafkaProduceHelper;
public ClientBalanceMonitorTotalKafkaTask(IKafkaProduce kafkaProduce)
{
_logger = LogFactory.GetLogger("ClientBalanceMonitorTotalKafkaTask");
onRspClientMonitorConsumerTopic = Environment.GetEnvironmentVariable("KafkaConfig_OnRspClientMonitorConsumerTopic");
reqClientMonitorTopicGroupId = Environment.GetEnvironmentVariable("KafkaConfig_ReqClientMonitorTopicGroupId");
reqClientMonitorTopic = Environment.GetEnvironmentVariable("KafkaConfig_ReqClientMonitorTopic");
_kafkaConsumer = new KafkaConsumerHelper(reqClientMonitorTopicGroupId, reqClientMonitorTopic);
kafkaProduceHelper = kafkaProduce;
}
public void Dispose()
{
_cts.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.Info("ClientBalanceMonitorTotalKafkaTask started");
Task.Run(() => ExecuteTask(_cts.Token), _cts.Token);
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.Info("ClientBalanceMonitorTotalKafkaTask stoped");
_cts.Cancel();
await Task.CompletedTask;
}
private async Task ExecuteTask(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
_kafkaConsumer.Subscribe(async msg =>
{
if (!string.IsNullOrEmpty(msg))
{
ClientBalanceMonitorFroTrsRequest req = JsonConvert.DeserializeObject<ClientBalanceMonitorFroTrsRequest>(msg);
var swapMonitorService = new SwapMonitorService(OptUserInfo.SystemUser);
// 执行任务
await Task.Run(() =>
{
Result result = new Result();
var res = new TrsRespone() { Req = req };
try
{
res.Res = swapMonitorService.GetMonitorForTrsRespone(req);
result.obj = res;
result.success = true;
}
catch (Exception ex)
{
result.msg = ex.Message;
result.success = false;
}
kafkaProduceHelper.Produce(onRspClientMonitorConsumerTopic, JsonConvert.SerializeObject(result));
}, cancellationToken);
}
});
}
catch (Exception ex)
{
_logger.Error("ClientBalanceMonitorTotalKafkaTask Exception", ex);
}
}
}
}
}