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 { /// /// 事件处理器 接口 /// /// public interface IIntegrationEventHandler { Task Handle(T @event); } /// /// 事件处理器 /// 重写Run 方法 /// 带有日志记录 /// /// public class IntegrationEventHandler : IIntegrationEventHandler where T : IntegrationEvent { public async Task Handle(T @event) { using var scope= GlobalContext.ServiceProvider!.CreateScope(); var logEventRepository= scope.ServiceProvider.GetRequiredService>(); var logExRepository= scope.ServiceProvider.GetRequiredService>(); 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(); } } }