You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

98 lines
2.6 KiB

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wood.Data.Repository;
using Wood.Entity.SystemManage;
using Wood.EventBus.Events;
using Wood.Util;
namespace Wood.EventBus
{
/// <summary>
/// 事件处理器 接口
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IIntegrationEventHandler<T>
{
Task Handle(T @event);
}
/// <summary>
/// 事件处理器
/// 重写Run 方法
/// 带有日志记录
/// </summary>
/// <typeparam name="T"></typeparam>
public class IntegrationEventHandler<T> : IIntegrationEventHandler<T> where T : IntegrationEvent
{
public async Task Handle(T @event)
{
using var scope= GlobalContext.ServiceProvider!.CreateScope();
var logEventRepository= scope.ServiceProvider.GetRequiredService<SqlSugarRepository<LogEventEntity>>();
var logExRepository= scope.ServiceProvider.GetRequiredService<SqlSugarRepository<LogExceptionEntity>>();
string status = "执行完成";
string errorMsg = "";
Stopwatch sw = new Stopwatch();
try
{
sw.Start();
await Run(@event, scope);
sw.Stop();
}
catch (Exception exception)
{
sw.Stop();
var exEntity = new LogExceptionEntity
{
Exception = exception.GetFullExceptionMessage(),
ExceptionStackTrace = exception.StackTrace,
Elapsed =(int)sw.ElapsedMilliseconds,
RequestParam = JsonConvert.SerializeObject(@event),
LogDateTime = DateTime.Now,
ActionName=@event.GetType().Name,
ControllerName=@event.GetType().Name,
Source = GetType().Name,
};
await logExRepository.InsertAsync(exEntity);
status = "错误";
errorMsg = exEntity.Exception;
Log.Error(exception, $"执行事件出错!【{exEntity.RequestParam}】");
}
#region 保存日志
if (@event.GetType().GetInterfaces().Any(it => it == typeof(IEventLog)))
{
LogEventEntity entity = new LogEventEntity()
{
Elapsed = (int)sw.ElapsedMilliseconds,
PublishDateTime = @event.CreateTime,
CreateTime = DateTime.Now,
PublishContent = JsonConvert.SerializeObject(@event),
EventName = typeof(T).Name,
EventId = @event.Id,
RetryCount = 0,
Status = status,
Remark = errorMsg
};
await logEventRepository.InsertAsync(entity);
}
#endregion
}
public virtual Task Run(T @event,IServiceScope scope)
{
throw new NotImplementedException();
}
}
}