public void Subscribe <T, TH>() where T : EventData where TH : IEventHandler { _eventBusManager.AddSub <T, TH>(); channel.QueueBind(queueName, exchangeName, typeof(T).Name); channel.QueueDeclare(queueName, true, false, false, null); var consumer = new EventingBasicConsumer(channel); consumer.Received += async(model, ea) => { string eventName = ea.RoutingKey; byte[] resp = ea.Body.ToArray(); string body = Encoding.UTF8.GetString(resp); _log.LogInformation(body); try { Type eventType = _eventBusManager.FindEventType(eventName); T eventData = (T)JsonConvert.DeserializeObject(body, eventType); IEventHandler <T> eventHandler = _eventBusManager.FindHandlerType(eventType) as IEventHandler <T>; await eventHandler.Handler(eventData); } catch (Exception ex) { throw ex; } }; channel.BasicConsume(queueName, true, consumer); }
private string InitializeEventConsumer(string queue) { var localQueueName = queue; if (string.IsNullOrEmpty(localQueueName)) { localQueueName = channel.QueueDeclare().QueueName; } else { channel.QueueDeclare(localQueueName, true, false, false, null); } var consumer = new EventingBasicConsumer(this.channel); consumer.Received += async(model, ea) => { string eventName = ea.RoutingKey; byte[] resp = ea.Body.ToArray(); string body = Encoding.UTF8.GetString(resp); try { Type eventType = _eventBusManager.FindEventType(eventName); var eventData = (EventData)JsonConvert.DeserializeObject(body, eventType); IEventHandler eventHandler = _eventBusManager.FindHandlerType(eventType) as IEventHandler; await eventHandler.Handler(eventData); } catch (Exception ex) { LogUtils.LogError(ex, "EventBusRabbitMQ", ex.Message); } }; channel.BasicConsume(localQueueName, autoAck: true, consumer: consumer); return(localQueueName); }